سؤال

I'm once more trying to solve a MYSQL related problem which sounds simple at first but is now causing me some headaches. I've read numerous snippets and experimented for a couple days but alas I have not had much success in terms of finding a perfect solution.

I have two tables. The first one contains phone calls, each phone call is represented by a row in the first table, which has the following three columns:

p_key (INT), call_date (DATE), call_time ( TIME )

My second table contains specific events, also with three columns:

event_id ( INT ), event_start ( DATETIME ), event_end ( DATETIME )

I would like to only count those entries from my first table - the call table - which do not fall within the time between start and end from the events table for the same date.

My main problem is, that there may be multiple entries in the events table for a single date ( Example: An event from 0800 - 1000 and another one from 1400 to 1600 on the same day ). Otherwise I could simply use a BETWEEN syntax.

I imagine it could be something to this affect:

SELECT
SUM(
   CASE WHEN t1.p_key != 0  
   THEN 1 ELSE 0 END
) AS brt,
SUM(
   CASE WHEN t1.p_key != 0  
    AND t1.call_time NOT BETWEEN TIME(t2.event_start) AND TIME(t2.event_end)
   THEN 1 ELSE 0 END
) AS net


FROM call_table t1 INNER JOIN event_table t2
ON t1.call_date = DATE(t2.event_start)
WHERE t1.call_date >= '2013-09-01'
AND t1.call_date <= '2013-09-30'
GROUP BY DAY(t1.call_date)

Unfortunately this query returns no results.

Can someone point me into a rough direction ?

P.s. I tried to find reference on how to format sample table data in my posts here on SO, but either I am blind or there is no specific reference. Since I've seen nicely formatted example table data, I know it is possible so an extra clue on that would be appreciated a lot as well.

UPDATE I managed to get some output, using a LEFT JOIN instead of INNER. Since I am no MySQL expert, I will go and -cough- count by hand if the results are correct.

هل كانت مفيدة؟

المحلول

You query should be then

SELECT 
  TIMESTAMP(call_date, call_time)
FROM 
  calls 
  LEFT JOIN events 
    ON TIMESTAMP(call_date, call_time)>event_start 
    AND timestamp(call_date, call_time)<event_end 
WHERE 
  event_start IS NULL

-see this fiddle.

For result in count, just do

SELECT 
  COUNT(calls.id)
FROM 
  calls 
  LEFT JOIN events 
    ON TIMESTAMP(call_date, call_time)>event_start 
    AND timestamp(call_date, call_time)<event_end 
WHERE 
  event_start IS NULL

نصائح أخرى

Try something like this:

SELECT *
FROM call_table t1
WHERE NOT EXISTS (
    SELECT * FROM event_table t2
    WHERE TIMESTAMP(t1.date, t1.time) BETWEEN t2.event_start AND t2.event_end)
)

This should give you all records in call_table that does not fall between any event start- and enddates in event_table. Add your own where-criteria and/or count() functions as you see fit.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top