这是从多个表中计数的最佳订购方式?

时间:2014-07-20 16:51:48

标签: php mysql sql

我想知道这些查询,我得到了一份工作,想要列出表user中的所有用户并计算他们的post photovideo 。并且可以选择按ASCDESC的这些计数限制进行排序 我已经尝试过它们但是看到子查询比连接快。我想知道这些查询之间的差异。为什么有时加入比子查询慢。加入最好只有两张桌子?这对我的工作来说最好吗?或者你可以建议另一种更好的解

SUB-QUERY

select
          user.*,
          (select count(*) from post where post.userid = user.id) postCount,
          (select count(*) from photo where photo.userid = user.id) photoCount,
          (select count(*) from video where video.userid = user.id) videoCount
        from user order by postCOunt desc limit $starrow 20

JOIN

SELECT u.id, 
        COUNT(DISTINCT p.id) AS postCount,
        COUNT(DISTINCT ph.id) AS photoCount,
        COUNT(DISTINCT v.id) AS videoCount
    FROM user u
        LEFT JOIN post p
            ON p.userid = u.id
        LEFT JOIN photo ph
            ON ph.userid = u.id
        LEFT JOIN video v
            ON v.userid = u.id
    GROUP BY u.id
    ORDER BY postCount LIMIT $startrow 20

HTML页面中按postCount DESC排序并进行分页的示例。

userid         postCount      photoCount    videCount
1              34             5             4
2              30             12            2
3              21             5             6
4              15             8             4
5              12             15            9
6              8              3             10

.. .. .. ..

1 个答案:

答案 0 :(得分:1)

您可以使用JOIN

以这种方式进行尝试
SELECT u.id, postCount, photoCount, videoCount
  FROM user u LEFT JOIN 
  (
    SELECT userid, COUNT(*) postCount
      FROM post
     GROUP BY userid
  ) p ON p.userid = u.id LEFT JOIN
  (
    SELECT userid, COUNT(*) photoCount
      FROM photo
     GROUP BY userid
  ) ph ON ph.userid = u.id LEFT JOIN
  (
    SELECT userid, COUNT(*) videoCount
      FROM video
     GROUP BY userid
  ) v ON v.userid = u.id
 ORDER BY postCount 
 LIMIT $startrow, 20