3

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

-------------------
| 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查询吗?

4

2 回答 2

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 列,并且您的“预期结果”不正确。我试图最大限度地适应它。

干杯

于 2012-05-27T19:10:52.507 回答
3
SELECT article_id, COUNT(article_id) AS votes
FROM votes_table
GROUP BY article_id
ORDER BY votes DESC;
于 2012-05-27T19:13:00.727 回答