having count with join

丶灬走出姿态 提交于 2021-02-09 11:45:49

问题


I want to find out which playlist have more than 2 songs. The statement works but I want the name of the playlist and the count() for the songs displayed. I think i have to use a join but I didn't get it how this should work. Can someone helps please?

playlist table
++++++++++++++
id
name

playlist_songs table
++++++++++++++++++++
song_id
playlist_id


SELECT p.name FROM playlist p 
WHERE p.id in (SELECT s.playlist_id counter FROM playlist_songs s
group by playlist_id
having count(song_id)>2);

回答1:


I want the name of the playlist and the count() for the songs displayed.

This one of the advantages of using JOIN over the IN predicate:

SELECT 
  p.name, 
  COUNT(song_id) counter
FROM playlist p 
INNER JOIN playlist_songs s ON  p.id = s.playlist_id 
GROUP BY playlist_id
HAVING COUNT(song_id) > 2;



回答2:


Try:-

SELECT
  p.name,
  count(s.song_id)
FROM
  playlist p
INNER JOIN
  playlist_songs s
ON
  p.id = s.playlist_id
GROUP BY
  p.name
HAVING
  COUNT(s.song_id) >= 2

This is SQL server syntax, but should work on Oracle.




回答3:


This is what you need:

SELECT p.name as name, count(*) as counter
FROM playlist p left outer join playlist_songs s on (p.id = s.playlist_id)
GROUP BY p.name
HAVING count(*) > 2



回答4:


Please try:

SELECT a.name
FROM
  playlist a INNER JOIN  playlist_songs b 
  ON a.id = b.playlist_id
GROUP BY a.name
HAVING COUNT(*) >1



回答5:


always use join if possible

SELECT p.name play_list,count(s.song_id) total_songs 
FROM playlist p 
INNER JOIN playlist_songs s 
ON p.id = s.playlist_id 
GROUP BY p.name 
HAVING COUNT(s.song_id) >= 2;


来源:https://stackoverflow.com/questions/14234081/having-count-with-join

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!