2013-01-03 132 views
2

我試着從一個MySQL表查詢在下一個時間間隔

+----+----------+---------+ 
| id | timefrom | timeto | 
+----+----------+---------+ 
| 0 | 08:30 | 10:30 | 
| 7 | 15:00 | 16:00 | 
| 2 | 17:00 | 17:30 | 
| 8 | 18:00 | 21:00 | 
+----+----------+---------+ 

查詢結果將是10:30至15:00

下一個可用的時間範圍查詢上可用「時間範圍」

edit1:id不在順序

謝謝!

+1

您是如何確定「*下一個可用時間範圍*」是「* 10:30到15:00 *」的? – eggyal

+0

該表實際上是一個每日時間段,從10:30到15:00之間的記錄中沒有其他條目顯示在表中,那麼它的下一個可用時間範圍 – Aries

+0

我沒有關注。 「16:00到17:00」和「17:30到18:00」是否也是如此? – eggyal

回答

2

我認爲你需要這樣的:

select t1.`timeto`, min(t2.`timefrom`) 
from 
    yourtable t1 inner join yourtable t2 
    on t1.`timeto`<t2.`timefrom` 
group by t1.`timeto` 
having 
    not exists (select null from yourtable t3 
       where t1.`timeto`<t3.`timeto` 
       and min(t2.`timefrom`)>t3.`timefrom`) 

(此方法僅當時間間隔不重疊)

+0

看到[這個小提琴](http://sqlfiddle.com/#!2/60ea1/1/1) – fthiella

+0

謝謝你,是的時間間隔不應該重疊 – Aries

+0

真棒查詢! :D幫我回答這一個:http://stackoverflow.com/a/15856847/114029 –

1

我想我會使用類似

SELECT 
    t1.*, 
    MIN(t2.`timefrom`) AS 'next (timefrom)', 
    TIMEDIFF(MIN(t2.`timefrom`),t1.`timeto`) AS 'interval' 
FROM `the_table` t1 
LEFT OUTER JOIN `the_table` t2 
ON t2.`timefrom` > t1.`timeto` 
GROUP BY t1.`timefrom`,t1.`timeto` 
#HAVING `next` IS NOT NULL 

取消對最後與在此使用INNER JOIN而不是LEFT OUTER JOIN相同。我選擇LOJ的原因是因爲我想查看錶格中的所有記錄,當然,這取決於您。

+0

謝謝你,它也工作 – Aries