简体   繁体   English

MySQL查询计数选票

[英]MySQL query to count votes

I have a table with the following columns: user_id, key, value, and flag. 我有一个包含以下列的表:user_id,键,值和标志。 The SELECT, FROM, WHERE, GROUP BY and ORDER BY work by themselves as expected. SELECT,FROM,WHERE,GROUP BY和ORDER BY自己按预期工作。 It's when I try to add the key to the table, I get an errors that says to check my syntax. 当我尝试将键添加到表时,出现一条错误,要求检查我的语法。 The key is the question and the value are the answers. 关键是问题,价值是答案。 I want a result that shows all the questions with all possible answers and a count of how often that answer occurred. 我想要一个显示所有问题以及所有可能答案的结果,以及该答案出现频率的计数。

SELECT value AS 'Answer', count(*) AS 'Total Votes'
FROM survey_data sd
INNER JOIN (SELECT key FROM sd GROUP BY key) T1 ON T1.key = sd.key
WHERE flag != 1
GROUP BY value
ORDER BY 'Total Votes' DESC

What am I missing here? 我在这里想念什么?

As a side note, when I run this query without the INNER JOIN, the result is not ordered DESC by 'Total Votes' -- does anyone know why or what the problem might be? 附带说明一下,当我在不使用INNER JOIN的情况下运行此查询时,结果未按“总投票数”对DESC进行排序-有人知道原因还是问题所在?

Thanks, Ryan 谢谢,瑞安

key is a reserved word. 键是保留字。

http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

put it within backticks (alt+96) or rename your field 将其放入反引号(alt + 96)或重命名您的字段

edit. 编辑。 If you use an alias with more than one word you have to use backtick too. 如果您使用的别名超过一个单词,则也必须使用反引号。 So change your order by clause in 因此,在

order by total votes desc without quotes total votes顺序排序,无引号

Put backtick before and after total votes. 在总选票之前和之后进行反选。 I don't see them in my post or even better change your field alias with a single word. 我在帖子中看不到它们,甚至更不用说用一个单词更改您的字段别名了。

Im an MSSQL guy so not sure if this will help, but try use fully qualified columns eg. 我是MSSQL专家,所以不确定是否会有所帮助,但请尝试使用完全限定的列,例如。 table.column table.column

SELECT sd.value AS 'Answer', count(sd.*) AS 'Total Votes'
FROM survey_data sd
INNER JOIN (SELECT sd.key FROM sd GROUP BY sd.key) T1 ON T1.key = sd.key
WHERE sd.flag != 1
GROUP BY sd.value
ORDER BY 'Total Votes' DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM