[英]SQL Query count issue
I've two tables artist
and members
. 我有两个桌子artist
和members
。 artist has zero to many relation with members. 艺术家与成员之间的关系为零。 (one artist may have 0 or many members) (一位艺术家可能有0个或很多成员)
So, I want to get all the fields of artist with the total number of members, that he has. 因此,我想获得所有具有艺术家总数的艺术家领域。
I write a query, but, it returns 0
count if there is no artist in the table (artist table is empty). 我写了一个查询,但是,如果表中没有艺术家(艺术家表为空),它将返回0
计数。 I am using this query 我正在使用此查询
SELECT a.artistname, count(m.id) as total
FROM artist a, members m
WHERE m.artist_id = a.id
It should simply not return anything if there is no artist. 如果没有艺术家,它应该不返回任何东西。
Thank you! 谢谢!
I'm assuming that your field name is artistname
in the artist
table, 我假设您的字段名称在artist
表中为artistname
,
The query should go like this: 查询应如下所示:
SELECT artist.artistname, COUNT(members.id) AS total_members
FROM artist
LEFT JOIN members ON members.artis_id = artist.id
GROUP BY artist.artistname
Use join, and to use sql count
you need to use group by
. 使用join和sql count
您需要使用group by
。
This should work: 这应该工作:
SELECT a.artistname,
count(m.id)
FROM artist a
LEFT JOIN members m
ON m.artist_id = a.id;
Perhaps the artistname is empty. 歌手姓名可能为空。 Did you check the data? 您检查数据了吗? You could try the following modified query: 您可以尝试以下修改后的查询:
SELECT a.artistname, count(m.id) as total
FROM artist a, members m
WHERE m.artist_id = a.id
AND a.artistname is NOT NULL
AND a.artistname <> '';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.