从多个表计数并在一个查询中返回所有计数值

时间:2014-07-15 22:37:46

标签: php mysql sql sql-order-by

我想从多个表中计数并在一个查询中返回所有计数值。我已经创建了SQL,感觉这个查询很慢。这是我说的最好的方式吗?如果没有,请建议我寻求更好的解决方案。因为有时需要超过15秒才能完成查询。谢谢。

这是我的数据库近似信息 表post 400行。
comment 3000行。
like 1000行 表view 6000行。

SQL

SELECT p.*,
     COUNT(c.id) as commentCount,
     COUNT(l.id) as likeCount,
     COUNT(c.id) as viewCount,
FROM post p
     LEFT JOIN comment c
           ON (p.id = c.postid) 
     LEFT JOIN like l
           ON (p.id = l.postid) 
     LEFT JOIN view v
           ON (p.id = v.postid) 
GROUP BY u.id
ORDER BY postCount DESC

表格帖子

CREATE TABLE `post` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`details` VARCHAR( 500 ) NOT NULL ,
`datetime` DATETIME NOT NULL
) ENGINE = MYISAM ;

表评论

CREATE TABLE `comment ` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`postid` INT( 10 ) NOT NULL ,
`details` VARCHAR( 500 ) NOT NULL ,
`datetime` DATETIME NOT NULL
) ENGINE = MYISAM ;

表格

CREATE TABLE `like` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`postid` INT( 10 ) NOT NULL ,
`datetime` DATETIME NOT NULL
) ENGINE = MYISAM ;

表格视图

CREATE TABLE `view` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`postid` INT( 10 ) NOT NULL ,
`ip` VARCHAR( 30) NOT NULL ,
`datetime` DATETIME NOT NULL
) ENGINE = MYISAM ;

1 个答案:

答案 0 :(得分:0)

查询速度很慢,因为您要沿多个维度进行聚合。这大大增加了数据的大小。一种解决方案是预先聚合数据:

SELECT p.*, c.cnt as commentCount, l.cnt as likeCount, v.cnt as viewCount,
FROM post p LEFT JOIN
     (select c.postid, count(*) as cnt
      from comment c
      group by c.postid
     ) c
     ON p.id = c.postid LEFT JOIN
     (select l.postid, count(*) as cnt
      from like l
      group by l.postid
     ) l
     ON p.id = l.postid LEFT JOIN
     (select v.postid, count(*) as cnt
      from view v
      group by v.postid
     ) v
     ON p.id = v.postid
GROUP BY p.id
ORDER BY postCount DESC;

此外,您的查询将返回三个计数的相同值 - 并且它们可能不准确。