简体   繁体   English

根据另一个表查询结果有限的表

[英]Query a table with limited results, based on another table

Let's assume I have tbl2, with a foreign key to another table (tbl1).假设我有 tbl2,有另一个表 (tbl1) 的外键。 For each record in the tbl1, we can have multiple or no records in tbl2.对于 tbl1 中的每条记录,我们可以在 tbl2 中有多个记录或没有记录。 I want to have only one record from tbl2 (the last record, based on time), which matches with a record on tbl1.我只想从 tbl2 中获得一条记录(最后一条记录,基于时间),它与 tbl1 上的一条记录匹配。 The following query only returns one record:以下查询仅返回一条记录:

select * from tbl2 where fk in (select id from tbl1 where some_criteria) order by time LIMIT 1 DESC select * from tbl2 where fk in (select id from tbl1 where some_criteria) order by time LIMIT 1 DESC

This query also returns all records from tbl2:此查询还返回 tbl2 中的所有记录:

select * from tbl2 where fk in (select id from tbl1 where some_criteria) order by time DESC select * from tbl2 where fk in (select id from tbl1 where some_criteria) 按时间顺序 DESC

I wanna have a row for each record from select id from tbl1 where some_criteria , having all details from the latest record exists in tbl2.我想为select id from tbl1 where some_criteria中存在最新记录的所有详细信息。

You want a lateral join, available since MySQL 8.0.14:你想要一个横向连接,从 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;

Here is a solution for old MySQL versions: Aggregate the tbl2 by fk to get the maximum time per fk.这是旧 MySQL 版本的解决方案:通过 fk 聚合 tbl2 以获得每个 fk 的最大时间。 Then use this result in your joins.然后在您的联接中使用此结果。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM