Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何对查询进行计数和分组以获得正确的结果?_Mysql_Sql_Count_Group By - Fatal编程技术网

Mysql 如何对查询进行计数和分组以获得正确的结果?

Mysql 如何对查询进行计数和分组以获得正确的结果?,mysql,sql,count,group-by,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

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

-------------------
| id | article_id |
-------------------
| 1  |      1     |
| 2  |      1     |
| 3  |      1     |
| 4  |      2     |
| 5  |      2     |
| 6  |      3     |
| 7  |      3     |
| 8  |      3     |
| 9  |      3     |
| 10 |      3     |
我想收到这样的东西(按投票顺序,从最大到最小):

你能帮我写一个合适的sql查询吗

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


干杯

我想创建一个“投票”专栏,你能更清楚地回答这个问题吗?你的意思是在这里(第一块)用ID作为文章的投票吗?你可以用一个变量来计算列。但大多数时候,人们认为他们需要它的原因是错误的。要么它应该在表中,要么在应用程序级别生成。我在添加它的同时,您发表了评论:-)虽然您对分析的要求完全正确,但从给出答案的角度来看,我包含了它。
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
SELECT article_id, COUNT(article_id) AS votes
FROM votes_table
GROUP BY article_id
ORDER BY votes DESC;