2

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.

4

2 回答 2

1

你的查询应该是

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

-看这个小提琴

对于计数结果,只需执行

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
于 2013-10-07T11:04:06.390 回答
1

尝试这样的事情:

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)
)

这应该会为您提供 call_table 中不位于 event_table 中任何事件开始日期和结束日期之间的所有记录。根据需要添加您自己的 where-criteria 和/或 count() 函数。

于 2013-10-07T10:58:29.190 回答