慢速查询使用"其中in"和#34;按选择计数排序"

时间:2014-06-19 16:05:39

标签: php mysql

我想显示来自用户的帖子,其中指定了用户,并且我在下面有两个表格。但它的查询非常慢。

用户

id | username
1  | name1
2  | name2
3  | name3
..
..

发布

id | poster_id | post_content
1  | 2
2  | 3
3  | 10
..
..

关注

followerid | followtoid
1          | 2
1          | 3
2          | 10
..
..

假设所有表格都有超过1000行。

这是 SQL

SELECT * 
FROM post 
WHERE poster_id IN (
    SELECT followtoid 
    WHERE followerid = $_SESSION['userid']
)

这是第二次演员也很慢。 我想按照总帖子的顺序列出所有会员。

 SELECT * 
 FROM user 
 ORDER BY (
     SELECT COUNT(id) 
     FROM post 
     WHERE post_id = user.id
) DESC;

3 个答案:

答案 0 :(得分:2)

尝试使用CREATE INDEXpost.useridpost.poster_idfollowtoid.followeriduser.user_id建立索引,并在您的查询中使用LEFT JOIN子句:< / p>

SELECT *
FROM user u
LEFT JOIN SELECT poster_id, COUNT(*) as count FROM post p GROUP BY poster_id  
ON (u.user_id = p.poster_id)
ORDER BY count DESC;

SELECT * FROM post AS p 
LEFT JOIN (SELECT followerid FROM followtoid) AS f
ON (p.userid=f.followerid)
WHERE p.userid = {$_SESSION['userid']}

答案 1 :(得分:1)

使用JOIN作为第一个查询

SELECT p.* 
FROM post p
    JOIN follow f ON p.post_id = f.followtoid
WHERE f.followerid = $_SESSION['userid']
第二次

JOIN以及GROUP BY

SELECT u.*, tbl.postCount
FROM user u
    JOIN (
        SELECT poster_id, COUNT(*) AS postCount
        FROM post p
        GROUP BY posterID
    ) tbl ON tbl.poster_id = u.id
ORDER BY postCount DESC

答案 2 :(得分:1)

您可以在没有子查询的情况下完成第二个查询:

SELECT u.*, COUNT(p.poster_id) as postCount
FROM user u
LEFT JOIN post p
    ON (u.user_id = p.poster_id)
GROUP BY u.user_id
ORDER BY postCount DESC;