在使用group by,rank和where时遇到sql问题 我试图从我的数据库中的表进行分组和排名,并且已经能够解决这个问题,所以现在我想使用列等于值的地方。 这是我的代码
SELECT g1.adnumber , g1.subject_id , g1.score ,
COUNT(*) AS rank FROM tbl_result AS g1
JOIN tbl_result AS g2
ON (g2.score, g2.adnumber) >= (g1.score, g1.adnumber)
AND g1.subject_id = g2.subject_id
GROUP BY g1.adnumber , g1.subject_id , g1.score
ORDER BY g1.subject_id , rank
where g1.adnumber = 'demonumber'
这是我得到的错误
#1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法 靠近'哪里g1.adnumber ='ctydemo'LIMIT 0,25'在第1行
答案 0 :(得分:2)
你不能只在最后放一个where
条款。您需要拥有正确的syntax
粗略地解释说,你必须有这个选择的顺序:
SELECT
*
[FROM]
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
[ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
[ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
在您的情况下,查询可能会这样工作。查看更改JOIN, ON, WHERE, AND
SELECT
g1.adnumber,
g1.subject_id,
g1.score,
COUNT(*) AS rank
FROM tbl_result AS g1
JOIN tbl_result AS g2
ON g1.subject_id = g2.subject_id
WHERE g1.adnumber = 'demonumber'
# not sure what you are trying with the next line
# AND (g2.score, g2.adnumber) >= (g1.score, g1.adnumber)
# maybe something like this:
AND g2.score >= g1.score
AND g2.adnumber >= g1.adnumber
GROUP BY
g1.adnumber,
g1.subject_id,
g1.score
ORDER BY
g1.subject_id,
g1.rank
答案 1 :(得分:2)
哪些陈述应该在分组之前?&按陈述排序。
这应该有效(未经测试)
SELECT
g1.adnumber , g1.subject_id , g1.score , COUNT(*) AS rank
FROM
tbl_result AS g1 JOIN tbl_result AS g2 ON (g2.score, g2.adnumber) >= (g1.score, g1.adnumber) AND g1.subject_id = g2.subject_id
WHERE
g1.adnumber = 'demonumber'
GROUP BY
g1.adnumber , g1.subject_id , g1.score
ORDER BY
g1.subject_id , rank
答案 2 :(得分:1)
您使用了错误的执行语法。在您的SQL where子句应放在group by 之前。请尝试以下SQL
SELECT g1.adnumber , g1.subject_id , g1.score ,
COUNT(*) AS rank FROM tbl_result AS g1
JOIN tbl_result AS g2
ON (g2.score, g2.adnumber) >= (g1.score, g1.adnumber)
AND g1.subject_id = g2.subject_id
where g1.adnumber = 'demonumber'
GROUP BY g1.adnumber , g1.subject_id , g1.score
ORDER BY g1.subject_id , rank;