在where子句中使用join值

时间:2011-08-09 10:23:30

标签: 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'。”

将WHERE包含在关键字中的最佳方法是什么?提前谢谢!

3 个答案:

答案 0 :(得分:3)

对于汇总列,您使用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

答案 1 :(得分:1)

 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


articlecount refers to which table field?
if articlecount  is in #_author table then you have to write item.articlecount 

or articles.articlecount

答案 2 :(得分:0)

尝试使用HAVING按汇总的valeus进行过滤:

WHERE item.published=1
HAVING count(articles.authorid) > 3
ORDER BY articlecount DESC 
相关问题