4

我目前有一张表,其中包含专辑名称、艺术家和标题(用于 Mp3)。在左侧的网页上,我目前使用以下方式显示所有专辑名称:

SELEC DISTINCT `album` FROM `mp3`

但我想在旁边显示每张专辑的数量,例如:

A Very Good Album (3)

表示该记录中有 3 个整数。我可以用 SQL 做到这一点吗?选择 Distinct,但还要找出该专辑有多少?

4

6 回答 6

3

试试这个:

SELECT `album`, COUNT(*) FROM `mp3` GROUP BY `album`
于 2012-12-13T14:46:25.010 回答
2

而不是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
于 2012-12-13T14:44:07.740 回答
1

你想要一个group by

select album, count(*)
from mp3
group by album
于 2012-12-13T14:44:07.257 回答
1

使用 group by 并像这样连接字符串

SELECT
    CONCAT(`album`, ' (', COUNT(*), ')') as album
FROM `mp3`
GROUP BY `album`
于 2012-12-13T14:45:28.237 回答
0

看看Count()Group By

于 2012-12-13T14:44:17.973 回答
0
SELECT DISTINCT CONCAT(album, ' (', COUNT(DISTINCT album), ')') AS album
FROM            mp3
GROUP BY        album
于 2012-12-13T14:46:45.760 回答