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

时间:2019-11-11 12:41:28

标签: mysql sql

我有一个电台的歌曲数据库,这些数据库是由各个程序添加到报告中的。我想选择专辑,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中找到的方法,但这使我可以按艺术家而不是专辑来对所有曲目进行计数。

DB表如下所示: tables

1 个答案:

答案 0 :(得分:2)

您可能需要不同的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和用逗号分隔的表名列表..来避免旧的隐式联接sintax,并使用显式联接sintax