简体   繁体   中英

which is the best way to order by count from multiple tables?

I'm wondering about these queries and I got a work that want to list all users in table user and count for their post photo and video . and can choose to view in sort by these count limit by ASC or DESC .
I've tried them both but see that sub-query is fast than join. i want to know the different between these queries. Why sometimes join is slower that a sub-query. is join best for only two tables? Is this both best for my work? or you can suggest another better solution.

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

Example in HTML page that order by postCount DESC and have paging.

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

.. .. .. ..

You can try it this way with 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM