我目前有一张表,其中包含专辑名称、艺术家和标题(用于 Mp3)。在左侧的网页上,我目前使用以下方式显示所有专辑名称:
SELEC DISTINCT `album` FROM `mp3`
但我想在旁边显示每张专辑的数量,例如:
A Very Good Album (3)
表示该记录中有 3 个整数。我可以用 SQL 做到这一点吗?选择 Distinct,但还要找出该专辑有多少?
试试这个:
SELECT `album`, COUNT(*) FROM `mp3` GROUP BY `album`
而不是DISTINCT
,这实际上是一个由 分组的基本COUNT()
聚合album
。
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
你想要一个group by
:
select album, count(*)
from mp3
group by album
使用 group by 并像这样连接字符串
SELECT
CONCAT(`album`, ' (', COUNT(*), ')') as album
FROM `mp3`
GROUP BY `album`
SELECT DISTINCT CONCAT(album, ' (', COUNT(DISTINCT album), ')') AS album
FROM mp3
GROUP BY album