如何计算和分组查询以获得正确的结果?

时间:2012-05-27 19:05:24

标签: mysql sql count group-by

我有问题,请查看我的数据库:

-------------------
| id | article_id |
-------------------
| 1  |      1     |
| 2  |      1     |
| 3  |      1     |
| 4  |      2     |
| 5  |      2     |
| 6  |      3     |
| 7  |      3     |
| 8  |      3     |
| 9  |      3     |
| 10 |      3     |

我想收到类似的东西(按票数排序,从最大到最小):

---------------------------
| id | article_id | votes |
---------------------------
| 1  |      3     |    5  |
| 2  |      1     |    3  |
| 3  |      2     |    2  |

你能帮我写一下正确的sql查询吗?

2 个答案:

答案 0 :(得分:4)

SET @currentRow = 0;
SELECT @currentRow := @currentRow + 1 AS id, t.article_id, t.c AS `votes`
FROM (
    SELECT article_id, count(*) as `c`
    FROM table_votes
    GROUP BY article_id
    ) t
ORDER BY t.c DESC

请注意,您无法在此上下文中选择此类ID列,并且您的“预期结果”不正确。我试图最大限度地适应它。

欢呼声

答案 1 :(得分:3)

SELECT article_id, COUNT(article_id) AS votes
FROM votes_table
GROUP BY article_id
ORDER BY votes DESC;
相关问题