用不同表中的条件计数

时间:2019-06-10 01:08:08

标签: mysql sql

我有4张桌子(歌曲,专辑和两个关系表)。

我有这两个查询需要合并:

-查询1)

SELECT l.name_language, count(s.id_song) 
FROM language as l
LEFT JOIN song_has_languages as s ON l.id_language = s.id_language
GROUP BY l.id_language
HAVING COUNT(s.id_song) > 0
ORDER BY name_language ASC

输出:

name_language | songs 
English       | 5     
Spanish       | 1          

-QUERY 2)

SELECT l.name_language, count(a.id_album) 
FROM language as l
LEFT JOIN album_has_languages as a ON l.id_language = a.id_language
GROUP BY l.id_language
HAVING COUNT(a.album)> 0
ORDER BY name_language ASC

输出:

name_language | albums
English       | 5
French        | 2

我的目标是输出:

name_language | total | 
English       | 10    | 
Spanish       | 1     | 
French        | 2     | 

我只想打印带有歌曲或专辑的语言。

1 个答案:

答案 0 :(得分:0)

您可以使用union all和聚合来做您想做的事情:

select l.name_language, sum(num_songs + num_albums) as total
from language l left join
     ((select shl.id_language, count(*) as num_songs, 0 as num_albums
       from song_has_languages shl
       group by  shl.id_language
      ) union all
      (select ahl.id_language, 0 as num_songs, count(*) as num_albums
       from album_has_languages ahl
       group by ahl.id_language
      )
     ) sa
     on sa.id_language = l.id_language
group by l.id_language, l.name_language;

您也可以用LEFT JOIN来表达这一点:

select l.name_language,
       ( coalesce(num_songs, 0) + coalesce(num_albums, 0) ) as total
from language l left join
     (select shl.id_language, count(*) as num_songs
      from song_has_languages shl
      group by  shl.id_language
     ) shl 
     on shl.id_language = l.id_language left join
     (select ahl. id_language, count(*) as num_albums
      from album_has_languages ahl
      group by ahl.id_language
     ) ahl
     on ahl.id_language = l.id_language;