如何修复sql中无效使用组函数的问题

问题描述 投票:0回答:1

我试图使用where编写一个代码来查找所选列中的特定行,但是当我添加where它不起作用时,在放入Where子句之前它工作正常。

所以有桌子qazxsw poi,stepstep_taken有qazxsw poi,qazxsw poi专栏; stepidtitlestep_taken

我希望得到用户已经超过2次的步骤标题。

所以我先写了

id

然后它显示了计数1到10的结果很好。

但是当我补充说

user_id

喜欢

step_id

我收到一个错误。

如何修复错误并获得仅大于计数值2的结果?

我想选择计数大于2的行但是当我使用SELECT title, COUNT(*) FROM step JOIN step_taken ON step.id = step_taken.step_id GROUP BY title ORDER BY COUNT(*); 子句时,它创建了一个错误。

sql where
1个回答
1
投票

您只能在WHERE COUNT(*) > 2 子句中使用聚合函数。将您的查询更改为:

SELECT title, count(*)
FROM step   
JOIN step_taken ON step.id = step_taken.step_id 
WHERE COUNT(*) > 2
GROUP BY title
ORDER BY COUNT(*);

请注意,使用列别名可以使查询更具可读性:

WHERE

请注意,在某些DBMS(如MySQL)中,您还可以使用HAVING子句中的列别名,即

SELECT title, count(*)
FROM step join step_taken
ON step.id=step_taken.step_id 
GROUP BY title
HAVING count(*)>2
ORDER BY count(*);
© www.soinside.com 2019 - 2024. All rights reserved.