我目前有一张包含专辑名称,艺术家和标题的表格(适用于Mp3s)。在我左侧的网页上,我目前使用以下方式显示所有相册名称:
SELEC DISTINCT `album` FROM `mp3`
但我想在旁边显示每张专辑的数量,例如:
A Very Good Album (3)
表示该记录中有3个entires。我可以用SQL做到这一点吗?选择Distinct,还要查看该专辑的数量是多少?
答案 0 :(得分:2)
而不是DISTINCT
,这实际上是由album
分组的基本COUNT()
aggregate。
SELECT
album,
COUNT(*) AS num_records
FROM
mp3
GROUP BY album
如果您想在SQL查询中的括号中使用它,请使用CONCAT()
。这可能最好留给您的应用程序进行显示。
SELECT
/* The album title, and count in () as one column as a single string */
/* like "A Very Good Album (3)" */
CONCAT(album, ' (', COUNT(*), ')') AS album
FROM
mp3
GROUP BY album
答案 1 :(得分:2)
试试这个:
SELECT `album`, COUNT(*) FROM `mp3` GROUP BY `album`
答案 2 :(得分:1)
您需要group by
:
select album, count(*)
from mp3
group by album
答案 3 :(得分:1)
使用group by并连接像这样的字符串
SELECT
CONCAT(`album`, ' (', COUNT(*), ')') as album
FROM `mp3`
GROUP BY `album`
答案 4 :(得分:0)
答案 5 :(得分:0)
SELECT DISTINCT CONCAT(album, ' (', COUNT(DISTINCT album), ')') AS album
FROM mp3
GROUP BY album