MySQL 8嵌套select with count

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL 8嵌套select with count相关的知识,希望对你有一定的参考价值。

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

我经历了谷歌,我找不到正确的答案。用count()或count(*)替换count(1)没有帮助。

MySQL8的查询应该是什么样的?

答案

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;
另一答案

你错过了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谓词而不是=

以上是关于MySQL 8嵌套select with count的主要内容,如果未能解决你的问题,请参考以下文章

MySQL with Node:如何返回嵌套数据

有没有办法在嵌套的 WITH 语句中包含 DELETE FROM 语句?

mysql进阶 with-as 性能调优

MySQL 在 select 语句中使用存储过程

MySql语句中select可以嵌套么,字段的重命名可以用中文么

具有多个嵌套 SELECT 的 MySQL INSERT