2014-10-29 56 views
0

我有這樣的SQL查詢中:SQL檢查日期時間爲48小時

SELECT t.contact_name as contact_name, t.contact_email as contact_email, 
    t.ticketnumber as ticketnumber, t.subject as subject 
FROM tickets t JOIN ticket_updates tu ON t.ticketnumber = tu.ticketnumber 
WHERE tu.type = 'update' AND 
    t.status = 'Awaiting Customer' AND 
    tu.datetime <= '2014-10-27 11:18:19' 
GROUP BY tu.ticketnumber 
order by tu.datetime DESC LIMIT 0,1 

這應該顯示了tickets記錄時在ticket_updates最新的行超過48小時前

我希望能夠自動更改statustickets如果已經ticket_updates48小時

內一直沒有在ticket_updates加我3排有下列日期時間:

2014-11-22 00:00:00 
2014-10-26 00:00:00 
2014-10-28 00:00:00 

所以最後一個是48小時之內,但其顯示在上面的查詢結果時,它不應該

+0

這真的有必要? 'SELECT t。*,tu。*'? – Kermit 2014-10-29 12:36:58

+0

不,我的意思是在我發佈之前將其取出。我已經從我的代碼中刪除了這個(不是它有所作爲) – user3864924 2014-10-29 12:59:34

+0

除了性能好處以外,在沒有任何聚合函數的情況下,使用GROUP BY子句經常是不恰當的,並且可能具有誤導性。 – Strawberry 2014-10-29 13:09:42

回答

0

你可以做內部的選擇(沒有測試):

SELECT t.contact_name as contact_name, 
     t.contact_email as contact_email, 
     t.ticketnumber as ticketnumber, 
     t.subject as subject 
FROM tickets t 
JOIN ticket_updates tu ON t.ticketnumber = tu.ticketnumber 
WHERE t.status = 'Awaiting Customer' 
AND t.ticketnumber NOT IN 
    (
    -- returns ticketnumbers that have recent updates 
    SELECT recentUpdates.ticketnumber 
    FROM ticket_updates recentUpdates 
    WHERE recentUpdates.type = 'update' AND recentUpdates.datetime => '2014-10-27 11:18:19' 
    ) 
GROUP BY tu.ticketnumber 
ORDER BY tu.datetime DESC LIMIT 0,1; 
+0

完美謝謝! – user3864924 2014-10-29 13:32:10

0

要加入的所有車票更新再滴加從過去的48小時的那些。你想使用最新的更新作爲連接的條件。

嘗試用此替換您的連接。

join (select Max (tu.datetime), tu.ticketnumber from ticket_updates tu 
    group by tu.ticketnumber) tu 
    on tu.t.ticketnumber = tu.ticketnumber