2014-11-21 29 views
0

我有一個MySQL表像獲取從表中的下一個最大的時間,一組輸入

Name | age |  time 
------+------+--------- 
x  | 23 | 21:00:01 
y  | 67 | 23:34:43 
z  | 90 | 12:45:34 
a  | 45 | 21:10:10 
b  | 3 | 23:45:00 

現在我需要找到具有時間只比給定的輸入大的輸入姓名和年齡。

說我有一個輸入21:00:01然後輸出將是21:10:10。我可以寫這個查詢,但我有一個巨大的輸入列表,每次我無法對每個輸入日期執行查詢。

我需要的是一個查詢,它將輸入列表作爲輸入,並將每個輸入的下一個大時間返回給我。我在這裏停留的任何解決方案,請

我試圖得到這樣的輸出時,有一個where子句像時間(「二十一點00分01秒」,...)

Name | age |  time | nexttime | nextname | 
------+------+-----------+---------------+--------------- 
x  | 23 | 21:00:01 | 21:10:10  | a 
y  | 67 | 23:34:43 | 23:45:00  | b 
z  | 90 | 12:45:34 | 21:00:01  | x 
a  | 45 | 21:10:10 | 23:34:43  | y 
b  | 3 | 23:45:00 |    | 

回答

1

認沽輸入表格,例如InputTimes。然後,你可以這樣做,因爲相關子查詢:

select it.*, 
     (select name 
     from table t 
     where t.time > it.time -- removed = 
     order by t.time 
     limit 1 
     ) as name, 
     (select age 
     from table t 
     where t.time > it.time -- removed = 
     order by t.time 
     limit 1 
     ) as age 
from InputTimes it; 
0

您是否正在尋找一種方式來獲得這樣的結果?

Name | age |  time | nexttime | nextname | 
------+------+-----------+---------------+--------------- 
x  | 23 | 21:00:01 | 21:10:10  | a 
y  | 67 | 23:34:43 | 23:45:00  | b 
z  | 90 | 12:45:34 | 21:00:01  | x 
a  | 45 | 21:10:10 | 23:34:43  | y 
b  | 3 | 23:45:00 |    | 

可以通過

select 
t.name, 
t.age, 
t.time, 
(select top 1 t2.time from myTable t2 where t2.time > t.time order by t2.time) as nexttime, 
(select top 1 t2.name from myTable t2 where t2.time > t.time order by t2.time) as nextname 
from myTable t 
+0

日Thnx奧勒來完成,我需要與上面相同。 – 2014-11-22 04:46:52

+0

用SQL語句發佈更新 – OlleR 2014-11-25 13:36:13

+0

哦,剛纔看到前面的文章剛剛給出了答案:) – OlleR 2014-11-25 13:37:26

相關問題