Mysql,按字段计数排序

时间:2013-12-30 12:02:40

标签: php mysql sorting

我有一张名为“purchase_albums”的表格

id  album_id    member_id   date
4      8              7     2013-12-24 08:17:54
5      9              7     2013-12-29 11:03:35
6      8              10    2013-12-24 08:17:54

我试图通过大多数购买的专辑对其进行排序。也就是说,它应该计算最重复的album_id并根据它进行排序。我的查询一直返回null。

$q="SELECT COUNT(album_id) as tot,album_id,date  FROM purchased_albums ORDER BY tot DESC";

4 个答案:

答案 0 :(得分:2)

请仔细阅读此代码,您可能会找到您的确切要求.........

  $q="SELECT COUNT(album_id) as tot,album_id,date FROM purchased_albums GROUP BY album_id ORDER BY album_id DESC";

答案 1 :(得分:1)

SELECT 
    COUNT(album_id) as tot,album_id,date  
FROM 
    purchased_albums 
GROUP BY album_id
ORDER BY tot DESC";

答案 2 :(得分:1)

您可以使用联接来获取每个相册的计数,然后按结果数量排序:

SELECT pa.*
FROM purchased_albums pa
INNER JOIN
(
    SELECT COUNT(*) qty_purchased, album_id
    FROM purchased_albums
    GROUP BY album_id
) c ON pa.album_id = c.album_id
ORDER BY c.qty_purchased DESC

答案 3 :(得分:1)

这样的事可以帮到你吗?

SELECT `album_id`, `date`, COUNT(*) `purchases`
FROM `purchased_albums`
GROUP BY `album_id`
ORDER BY `purchases` DESC

挑选出更多的专辑,例如购买的专辑。 3次,使用HAVING

SELECT `album_id`, `date`, COUNT(*) `purchases`
FROM `purchased_albums`
GROUP BY `album_id`
HAVING `purchases` > 3
ORDER BY `purchases` DESC