mysql - 在 where 子句中使用连接值

标签 mysql left-join

我想对连接表中的值使用 where 语句。想不通:

SELECT item.*, count(articles.authorid) AS articlecount 
FROM #_authors AS item 
LEFT JOIN #_articles AS articles ON (articles.authorid = item.id) 
WHERE item.published=1 
AND articlecount>3 
ORDER BY articlecount DESC

orderby 工作正常,但是当我添加“AND articlecount>3”时出现错误:“#1054 - ‘where 子句’中的未知列‘articlecount’”。

在 articlecount 中包含 WHERE 的最佳方法是什么?提前致谢!

最佳答案

对于聚合列,您可以使用 HAVING,如下所示:

SELECT item.*, count(articles.authorid) AS articlecount 
FROM #_authors AS item 
LEFT JOIN #_articles AS articles ON (articles.authorid = item.id) 
WHERE item.published=1 
GROUP BY 1,2,3,4,5,6,7,8 -- assuming there are 8 columns in item
HAVING count(articles.authorid) > 3 
ORDER BY 9 DESC -- assuming there are 8 columns in item

关于mysql - 在 where 子句中使用连接值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6994696/

相关文章:

sql - 如何将数据库表的行合并为一行

左连接后MYSQL求和不同值

java - 如何检索数据库中一列字段中的多个数据并将其逐个显示到输入字段中

php - 即使 mysql 表中有值,SQL 查询也不会返回值

MySQL 全文搜索、整理和不间断空格

php - 使用 LEFT OUTER JOIN 连接多个表

php - cakePHP 中的 hasMany 组合框

mysql - 在mysql中使用group by,报错1055

sql - join语句的操作顺序

mysql - [SQL]如何使用 LEFT JOIN 和 DELETE 删除连接表列上包含 NULL 值的所有行