gpt4 book ai didi

mysql - 从多个表中选择多个值的计数

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

我有一个广播电台的歌曲数据库,由各个节目添加到报告中。我想选择专辑、album_id、专辑中的歌曲数以及单个艺术家的报告历史记录中的专辑出现次数。所以我想要以下结果:

| album_id | album_name | track_count | report_occurrence_count |
|---------------------------------------------------------------|
| 1 | Name 1 | 10 | 25 |
| 2 | Name 2 | 15 | 65 |
| 3 | Name 3 | 23 | 11 |

编辑:从中选择值的相关表格:

| album     | artist     | track       | report_track   |
|-------------------------------------------------------|
| id | id | id | id |
| artist_id | name | album_id | report_id |
| name | ... | artist_id | track_id |
| ... | ... | ... | ... |

我可以获取轨道计数或报告出现次数,但不能同时获取两者。我尝试了以下方法:

SELECT al.id as album_id, al.name, al.identifier, count(tr.album_id) as track_count, 
count(rt.track_id) as report_occurrence
FROM playlist__album as al, playlist__artist as ar, playlist__track as tr,
playlist__report_track as rt
WHERE al.artist_id = ar.id
and tr.album_id = al.id
and rt.track_id = tr.id
and ar.id = 39887
group by album_id

但这为我提供了 track_count 和 report_occurrence_count 列的 report_occurrence 计数。如果我将 count(rt.track_id) 作为 report_occurrence 删除,我将获得正确的 track_count 值。我试过在 here 中找到的方法但这让我可以按艺术家而不是按专辑计数所有轨道。

数据库表是这样的: tables

最佳答案

你可能需要不同的轨道 track_no

SELECT al.id as album_id
, al.name
, al.identifier
, count(distinct tr.track_no) as track_count
, count(rt.track_id) as report_occurrence
FROM playlist__album as al
INNER JOIN playlist__artist as ar ON al.artist_id = ar.id
INNER JOIN playlist__track as tr ON and tr.album_id = al.id
INNER JOIN playlist__report_track as rt ON rt.track_id = tr.id
WHERE ar.id = 39887
group by album_id

并且您应该避免基于 where 和逗号分隔的表名列表的旧隐式连接语法,并使用显式连接语法。

关于mysql - 从多个表中选择多个值的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58801577/

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