[英]Query latest insert data of X type before latest insert data of Y type MySQL
我有一個簡單的數據
'crossType' [1-8] | 'isLocal' [1-2] | 'dayCross' [int] | TIMESTAMP
我想找到的最新的插入數據'isLocal' = 1
之前的最新插入數據'crossType' = 2
那么我的輸出是'dayCross'
如
'crossType' [1-8] | 'isLocal' [1-2] | 'dayCross' [int] | TIMESTAMP
1 | 1 | 3 | xx:xx:xxxx
2 | 2 | 5 | xx:xx:xxxx
5 | 2 | 7 | xx:xx:xxxx
3 | 1 | 9 | xx:xx:xxxx
2 | 1 | 10 | xx:xx:xxxx
最新的插入數據'crossType'= 2是
2 | 2 | 5 | xx:xx:xxxx
然后最新的插入數據'isLocal'= 1
3 | 1 | 9 | xx:xx:xxxx
我的輸出將是9
這個問題的查詢語句是什么。
謝謝。
嘗試這個:
select dayCross
from your_table
where isLocal = 1
and timestamp < ( select max(timestamp)
from your_table
where crossType = 2
)
order by timestamp desc
limit 1;
外部查詢將返回最新的dayCross
其timestamp
早於crossType
2的最新timestamp
(在子查詢中找到)。
這是您的查詢:
SELECT dayCross FROM testing.new_table
WHERE isLocal='1' AND `timestamp` <
(select max(`timestamp`) from testing.new_table where crossType='2')
ORDER BY `timestamp` DESC LIMIT 1;
您可以從數據中以'crossLocal'= 2的最新插入數據中獲取以'isLocal'= 1的最新插入dayCross。
數據如下:
crossType isLocal dayCross timestamp
1 1 3 2017-02-04 00:50:00
2 2 5 2017-02-04 00:40:00
5 2 7 2017-02-04 00:30:00
3 1 9 2017-02-04 00:20:00
2 1 10 2017-02-04 00:10:00
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.