[英]Query a table with limited results, based on another table
假設我有 tbl2,有另一個表 (tbl1) 的外鍵。 對於 tbl1 中的每條記錄,我們可以在 tbl2 中有多個記錄或沒有記錄。 我只想從 tbl2 中獲得一條記錄(最后一條記錄,基於時間),它與 tbl1 上的一條記錄匹配。 以下查詢僅返回一條記錄:
select * from tbl2 where fk in (select id from tbl1 where some_criteria) order by time LIMIT 1 DESC
此查詢還返回 tbl2 中的所有記錄:
select * from tbl2 where fk in (select id from tbl1 where some_criteria) 按時間順序 DESC
我想為select id from tbl1 where some_criteria
中存在最新記錄的所有詳細信息。
你想要一個橫向連接,從 MySQL 8.0.14 開始可用:
select *
from tbl1
left outer join lateral
(
select *
from tbl2
where tbl2.fk = tbl1.id
order by time desc
limit 1
) newest_tbl2 on true;
這是舊 MySQL 版本的解決方案:通過 fk 聚合 tbl2 以獲得每個 fk 的最大時間。 然后在您的聯接中使用此結果。
select *
from tbl1
left outer join
(
select fk, max(time) as max_time
from tbl2
group by fk
) mx on mx.fk = tbl1.id
left outer join tbl2 on tbl2.fk = mx.fk and tbl2.time = mx.max_time;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.