MySQL 8嵌套带计数的选择

时间:2019-01-24 09:25:10

标签: mysql sql database mysql-8.0

SELECT mapname, 
    (SELECT count(1)+1 FROM ck_bonus b WHERE a.mapname=b.mapname AND a.runtime > b.runtime AND a.zonegroup = b.zonegroup AND b.style = %i) AS rank, 
    (SELECT count(1) FROM ck_bonus b WHERE a.mapname = b.mapname AND a.zonegroup = b.zonegroup AND b.style = %i) as total 
    FROM ck_bonus a WHERE steamid = '%s' AND style = %i;

这段代码过去在MySQL8更新之前可以正常工作,但现在因此错误而吐出

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
 'rank, (SELECT count(1) FROM ck_bonus b WHERE a.mapname = b.mapname AND a.zonegro' at line 1

我浏览了google,但找不到正确的答案。 用count()或count(*)替换count(1)并没有帮助。

对于MySQL8,此查询应该是什么样?

2 个答案:

答案 0 :(得分:1)

rank是MySql 8中的reserved word

因此,请使用另一个别名,或反选别名。

在MySql 8中,您可以使用window functions

SELECT 
 mapname, 
 DENSE_RANK() OVER (PARTITION BY mapname, zonegroup, steamid, style ORDER BY runtime DESC) AS `rank`,
 COUNT(*) OVER (PARTITION BY mapname, zonegroup, steamid, style) AS total
FROM ck_bonus 
WHERE steamid = '%s' AND style = %i;

答案 1 :(得分:0)

您错过了outersubquery中的单引号:

SELECT mapname, 
       (SELECT count(1) FROM ck_bonus b WHERE a.mapname = b.mapname AND a.runtime > b.runtime AND a.zonegroup = b.zonegroup AND b.style = '%i') + 1 AS rnk, 
       (SELECT count(1) FROM ck_bonus b WHERE a.mapname = b.mapname AND a.zonegroup = b.zonegroup AND b.style = '%i') as total 
FROM ck_bonus a 
WHERE steamid = '%s' AND style = '%i';

我怀疑您需要LIKE谓词而不是=