MySQL在另一个表上选择计数查询

时间:2011-10-10 06:33:01

标签: mysql sql count query-optimization table-locking

我有三个表的简单文章应用程序:

article 
id, title,  body,   user_id

comment
id, article_id, user_id,    body

user
id, username

在目标网页上,我想显示最新文章标题,其中包含作者姓名和文章评论总数。主要问题是如何获得文章的评论总数,我没有把它弄好。我应该得到以下输出:

title           username    total_comments
article 2       user2           0
article 1       user1           2

在我的实际应用程序中,我在文章表中添加了一个列,用于查看文章的总评论数。将新注释添加到系统时,此列会更新。这样做的问题是在添加新注释时文章表被锁定。在我的应用程序中,每分钟都会添加很多注释。所以我试图通过重写SQL查询来避免锁定文章表。

以下是一些测试数据:

CREATE TABLE `article` (
`id` INT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` VARCHAR( 100 ) NULL ,
`body` LONGTEXT NULL ,
`user_id` INT NULL
) ENGINE = MYISAM ;


CREATE TABLE `comment` (
`id` INT NULL AUTO_INCREMENT PRIMARY KEY ,
`article_id` INT NULL ,
`user_id` INT NULL ,
`body` LONGTEXT NULL
) ENGINE = MYISAM ;

CREATE TABLE `user` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 50 ) NOT NULL
) ENGINE = MYISAM ;


INSERT INTO `test`.`user` (
`id` ,
`username`
)
VALUES (
NULL , 'user1'
), (
NULL , 'user2'
);


INSERT INTO `test`.`article` (
`id` ,
`title` ,
`body` ,
`user_id`
)
VALUES (
NULL , 'article 1', 'body article 1', '1'
), (
NULL , 'article 2', 'body article 2', '2'
);

INSERT INTO `test`.`comment` (
`id` ,
`article_id` ,
`user_id` ,
`body`
)
VALUES (
NULL , '1', '1', 'body comment to article 1'
), (
NULL , '1', '1', 'body comment to article 1'
);

4 个答案:

答案 0 :(得分:3)

SELECT a.title AS title, u.username AS username, count(c.id) as total_comments FROM articles a
   LEFT JOIN comments c ON c.article_id = a.id
   LEFT JOIN users u ON a.user_id = u.id
GROUP BY a.id

答案 1 :(得分:2)

这样的事情怎么样,现在无法测试,所以它可能有错误。

SELECT a.title, u.username, COUNT(*) total_comments
FROM article a
  JOIN user u ON (u.id=a.user_id)
  LEFT OUTER JOIN comment c ON (c.article_id=a.id)
GROUP BY a.title, u.username

答案 2 :(得分:1)

如果您尝试这样做,它会回答吗?

SELECT a.title AS title, 
             u.username AS username, 
             count(c.id) AS total_comments 
 FROM articles a, comments c, users u
 WHERE  a.user_id =u.id
    And a.id=c.articles_id
    And c.user_id = u.id 

或者使用内部语法

SELECT a.title AS title, 
             u.username AS username, 
             count(c.id) AS total_comments 
 FROM articles a 
 INNER JOIN comments c ON c.article_id = a.id 
                                          AND c.user_id=u.id
 INNER JOIN users u ON a.user_id = u.id 
 GROUP BY a.id

答案 3 :(得分:1)

SELECT article.title AS title, COUNT(  'comment.id' ) AS total_comment, user.username AS username
FROM article
JOIN COMMENT ON comment.article_id = article.id
JOIN user ON user.id = article.user_id
GROUP BY article.id