Mysql 如何在 WHERE 语句中使用连接表中行的 COUNT 值?
像这样:
COUNT(i.t_1) AS total_images
WHERE total_images > 2
引发错误:
Unknown column "total_images" in where clause
如果这样:
WHERE COUNT(i.t_1) > 2
引发错误:
Invalid use of group function
如何正确地做到这一点?
如果需要,我会发布完整的声明。
此查询的含义是选择 join(images) 表中照片最多的 1 个广告。
谢谢 ;)
Like that:
COUNT(i.t_1) AS total_images
WHERE total_images > 2
Throws an error:
Unknown column "total_images" in where clause
If this way:
WHERE COUNT(i.t_1) > 2
Throws an error:
Invalid use of group function
How to do it right way?
If need i'll post full statement.
The meaning of this query to pick the 1 ad with the most photos inside joined(images) table.
Thanks ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
WHERE 子句只能用于逐行过滤表/派生表中的行。要根据聚合结果进行过滤,您需要使用 HAVING 而不是 WHERE:
The WHERE clause can only be used to filter rows in the table / derived table on a row-by-row basis. To filter based on the results of an aggregation you need to using HAVING instead of WHERE:
如果您确实只是在寻找“包含最多照片的 1 个广告”,您可能需要类似以下内容:
select i.t_1,count(*) n ... group by i.t_1 order by n desc limit 1
If you're really just looking for the "1 ad with the most photos", you might want something like:
select i.t_1,count(*) n ... group by i.t_1 order by n desc limit 1