0

大家好,我不知道......为什么这个查询不起作用:

      SELECT article.topic, article.ID, 
      (
      SELECT COUNT(*) FROM comment
      WHERE article.ID_art = comment.foreign_ID_art
      GROUP BY foreign_ID_art
      ) 
      AS mycount

      FROM article
      WHERE article.mycount = '0'
4

3 回答 3

1

mycount不是表格的一列article。正确的写法是:

 SELECT article.topic,
        article.ID   ,
        ( SELECT  COUNT(*)
        FROM     COMMENT
        WHERE    article.ID_art = comment.foreign_ID_art
        GROUP BY foreign_ID_art
        )
        AS mycount
 FROM  article HAVING mycount = 0

实现相同结果的另一种方法,但以一种更有效的方式(假设存在适当的索引):

SELECT article.topic,
       article.ID
FROM   article
       LEFT JOIN COMMENT
       ON     article.ID_art = comment.foreign_ID_art
WHERE  comment.foreign_ID_art IS NULL

最终,最好将每篇文章的评论计数article作为列存储在表中,comment_count并在添加新评论时增加它。那么查询可以简化为:

SELECT article.topic,
       article.ID
FROM   article
WHERE  article.comment_count = 0

使用索引comment_count将非常有效。

于 2012-05-15T20:40:54.173 回答
1
SELECT article.topic, article.ID, 
  (
  SELECT COUNT(*) FROM comment
  WHERE article.ID_art = comment.foreign_ID_art
  GROUP BY foreign_ID_art
  ) 
  AS mycount

FROM article
HAVING mycount = '0'
于 2012-05-15T20:42:56.533 回答
0

您不能在 where 子句中使用列别名。也许你可以做类似的事情

select *
(SELECT article.topic, article.ID,        
(       
SELECT COUNT(*) FROM comment       
WHERE article.ID_art = comment.foreign_ID_art       
GROUP BY foreign_ID_art       
)        
AS mycount        
FROM article) mytab       
from myab 
WHERE mytab.mycount = 0 
于 2012-05-15T20:37:59.887 回答