[英]Select from MySQL based on another table's total result of certain column match
I have two tables in my DB 我的数据库中有两个表
Genre contains: id, genre_id
流派包含:
id, genre_id
Music contains: id, song_id, genre_id
音乐包含:
id, song_id, genre_id
I want to show the result of: 我想显示结果:
SELECT * FROM Genre WHERE total number of rows in Music
WHERE Genre.genre_id = Music.genre_id > 4
I have been scratching my head for hours trying to get it using JOIN
but I couldn't get how logically to solve it then put it in mysql code. 数小时以来,我一直在努力尝试使用
JOIN
来获取它,但我无法从逻辑上解决它,然后将其放入mysql代码中。
Your desired output is only a couple of minor syntax changes off from a valid query: 您所需的输出只是有效查询的一些次要语法更改:
SELECT *
FROM Genre g
WHERE (SELECT COUNT(*) FROM Music m WHERE g.genre_id = m.genre_id) > 4
While that's probably the most understandable way of doing it, a combination of LEFT OUTER JOIN
, GROUP BY
and HAVING
may be more efficient: 尽管这可能是最容易理解的方式,但将
LEFT OUTER JOIN
, GROUP BY
和HAVING
组合起来可能会更有效:
SELECT g.id, g.genre_id
FROM Genre g
LEFT OUTER JOIN Music m ON m.genre_id = g.genre_id
GROUP BY g.id, g.genre_id
HAVING COUNT(*) > 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.