gpt4 book ai didi

mysql - 使用嵌套查询和内连接清理 SQL 查询

转载 作者:行者123 更新时间:2023-11-29 09:29:24 26 4
gpt4 key购买 nike

我一直在尝试通过一些我为自己开发的练习题重新认识 SQL,但正在努力寻找更好的方法来解决以下问题:

播放列表

id           title
1 Title1
2 Title2

播放列表剪辑

id  playlist_id clip_id
1 Title1 3
2 Title2 1

播放列表标签

playlist_id tag_id
1 1
1 2
2 2

ClipsTags 是两个完全独立的表,我使用 playlist_tagsplaylist_clips 进行连接将它们添加到 playlists 表中,以表示双向一对多关系。

我想选择具有给定标题的所有播放列表,并且具有查询中提供的所有标签(在本例中为 [1, 2]),而不仅仅是“至少其中一个”。

这是我想出的:

select p_clips.* from
(
select p.id, p.title, count(pc.id) as number_of_clips
from playlists p
left join playlist_clips pc on p.id = pc.playlist_id
where p.title like "Test1"
group by id
) as p_clips

inner join

(
select *
from playlists p
left join playlist_tags pt on p.id = pt.playlist_id
where pt.tag_id in (1, 2)
group by id
having count(*) = 2
) as p_tags

on p_clips.id = p_tags.id

虽然,从我的测试来看,我发现这是可行的,但它看起来并不是特别优雅,而且我还认为它在性能方面并不是非常有效。 (我已从本示例的代码中删除了不相关的参数,例如 select 参数。)

什么是更干净的方法来解决这个问题,或者至少是一个更优化的方法?

预期结果:

id  title
260 Title1

编辑:我为我最初令人困惑的帖子道歉,我已尝试清理我的表格及其包含的信息。

最佳答案

I wanted to select all the playlists that have a given title, and have ALL of the tags provided in the query (in this example [1, 2]), not just "at least one of them".

您根本不需要剪辑表。您不需要子查询中的左联接播放列表表。

这表明:

select p.*
from playlists p join
(select pt.playlist_id
from playlist_tags pt
where pt.tag_id in (1, 2)
group by id
having count(*) = 2
) pt
on p.id = pt.playlist_id
where p.title like 'Test1';

您也可以在没有子查询的情况下表达此内容:

select p.*
from playlists p join
playlist_tags pt
on p.id = pt.id
where p.title like 'Test1' and
pt.tag_id in (1, 2)
group by p.id
having count(*) = 2

关于mysql - 使用嵌套查询和内连接清理 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59018101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com