gpt4 book ai didi

php - 计算另一个表中与其 id 关联的行数

转载 作者:行者123 更新时间:2023-11-29 12:02:37 27 4
gpt4 key购买 nike

嗨,我们有 3 个音乐表,在 MySql 中是这样的:

第一个表:

第一个表是存在音乐播放列表的播放列表表。

playlistId           playlistTitle          categoryId

1 hello 0
2 wow 0
3 wi-fi 0
4 awesome 0
5 sixer 1
6 four 1
7 boundary 2

第二个表:

第二个表用于 songRelation 表,其中每个播放列表都与他们的歌曲关联

playlistId            songId

1 4
1 3
1 43
1 57
1 98
2 56
2 67
2 90
2 78
3 98
3 78
3 89
43 90

第三个表:第三个表用于存在歌曲详细信息的歌曲

songId                songTitle

4 hello
3 real hero
43 singalone
57 awesom
98 really
78 sakaka
98 shikwa
89 moha
90 hello2
67 Sneh

实际上我正在获取如下结果:

playlistId  songId    categoryId songTitle

1 4 0 hello
1 3 0 real hero
2 56 0 singalone
2 67 0 Sneh
3 78 0 sakaka
3 98 0 Shikwa

其中每个 playlistId 将包含其前 2 个songIdcategoryId以及songTitle`。

但我想计算每个playlistId的总歌曲

获得我想要的总歌曲结果后将是这样的:

playlistId  songId    categoryId songTitle       totalSong

1 4 0 hello 5
1 3 0 real hero 5
2 56 0 singalone 4
2 67 0 Sneh 4
3 78 0 sakaka 3
3 98 0 Shikwa 3

这里是 jsfiddle 演示,其中查询没有 totalSong http://sqlfiddle.com/#!9/7eda7/5

将添加什么子查询来获得上述期望的结果。

最佳答案

要准确获得您要求的结果,请使用:

select p.playlistId, 
s.songId,
p.categoryId,
s.songTitle,
(select count(*) from songRelation where playlistId = p.playlistId) totalSong
from playlist p
inner join songRelation r on p.playlistId = r.playlistId
inner join song s on r.songId = s.songId

在主查询上使用 group by 会合并详细的歌曲数据,迫使您运行两个查询:一个用于详细信息(前 4 个字段),第二个查询用于恢复总计(最后一列)。使用此解决方案,您可以获得所有详细数据和总数,子查询将按照您询问的方式恢复每个播放列表的歌曲数量。

更新:

rlanvin 建议的这种方式应该会使查询更快,因为在计算每行的子查询时,它只计算一次,然后连接到主查询。结果是一样的:

select p.playlistId, 
s.songId,
p.categoryId,
s.songTitle,
r1.totalSong
from playlist p
inner join songRelation r on p.playlistId = r.playlistId
inner join song s on r.songId = s.songId
inner join (SELECT playlistid, COUNT(songId) as totalSong from songRelation group by playlistid) r1 on p.playlistId = r1.playlistId

关于php - 计算另一个表中与其 id 关联的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32120608/

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