首页 > 解决方案 > MySQL - 返回不同的 ID,其中相同 ID 的所有行都没有特定的字段值

问题描述

我有两个连接的查询:

SELECT v.top_id, m.related_type
FROM content_v_table v
JOIN content_e_table e
    ON v.child_id = e.winning_child_id
LEFT JOIN content_media m
    ON v.child_id = m.child_id;

返回此数据:

TOP_ID RELATED_TYPE
1 图像
1 图像
1 视频
2 NULL
3 图像
3 图像
4 视频
4 视频
4 视频
4 图像
5 图像

我想为具有相同 TOP_ID 的任何行返回在“RELATED_TYPE”列中没有“视频”值的唯一 TOP_ID。在这种情况下,查询应该返回这些 TOP_ID:

2
3
5

谢谢!

标签: mysql

解决方案


在 MySQL 8.x 中,您可以执行以下操作:

with 
x as (
  my_query_with_two_joins
)
select distinct id
from x
where id not in (select id from x where type = 'video')

推荐阅读