将 MySQL join 返回的结果限制为 1
Posted
技术标签:
【中文标题】将 MySQL join 返回的结果限制为 1【英文标题】:Limit the results returned by MySQL join to 1 【发布时间】:2021-06-24 20:47:25 【问题描述】:我正在对两个表进行 JOIN,右侧有多个 ON 子句的结果:e.ID = ti.event_id
。如何将连接返回的结果限制为 1?有点像LIMIT 1
events_detail
tbl:
ID | event_code
---------------
1 | 123-abc
2 | 234-bcd
3 | 345-cde
events_start_end
tbl:
id | event_id | start_time | end_time
-------------------------------------
1 | 1 | 12:00 | 17:00
2 | 1 | 13:00 | 15:00
3 | 2 | 12:00 | 15:00
4 | 3 | 07:00 | 10:00
5 | 3 | 08:00 | 11:00
当前查询:
SELECT e.ID, e.event_code, ti.start_time, ti.end_time
FROM events_detail AS e
LEFT JOIN events_start_end AS ti
ON e.ID = ti.event_id
WHERE e.event_status = 'A';
实际结果:
ID | event_code | start_time | end_time
---------------------------------------
1 | 123-abc | 12:00 | 17:00
1 | 123-abc | 13:00 | 15:00
2 | 234-bcd | 12:00 | 15:00
3 | 345-cde | 07:00 | 10:00
3 | 345-cde | 08:00 | 11:00
首选结果:
ID | event_code | start_time | end_time
---------------------------------------
1 | 123-abc | 12:00 | 17:00
2 | 234-bcd | 12:00 | 15:00
3 | 345-cde | 07:00 | 10:00
【问题讨论】:
【参考方案1】:使用ROW_NUMBER()
:
SELECT e.*
FROM (SELECT e.ID, e.event_code, ti.start_time, ti.end_time,
ROW_NUMBER() OVER (PARTITION BY e.event_code ORDER BY t1.start_time) as seqnum
FROM events_detail e LEFT JOIN
events_start_end ti
ON e.ID = ti.event_id
WHERE e.event_status = 'A'
) e
WHERE seqnum = 1;
【讨论】:
你能解释一下这是做什么的吗?我对 SQL 不是很熟悉 除了我遇到问题的连接之外,我还有其他几个连接要做 - 您的答案看起来像是将原始查询包装在另一个查询中,这使得应用变得困难【参考方案2】:我最终通过使用子查询解决了这个问题:
SELECT `e`.`ID`,
`e`.`event_code`,
`ti`.`start_time`,
`ti`.`end_time`
FROM `events_detail` AS `e`
LEFT JOIN `events_start_end` AS `ti`
ON `ti`.`id` = (
SELECT `id`
FROM `events_start_end`
WHERE `events_start_end`.`event_id` = `e`.`ID`
LIMIT 1
)
WHERE `e`.`event_status` = 'A'
【讨论】:
以上是关于将 MySQL join 返回的结果限制为 1的主要内容,如果未能解决你的问题,请参考以下文章
根据 JOIN ON 参数或 WHERE 参数限制 SQL 结果