我想显示来自用户的帖子,其中指定了用户,并且我在下面有两个表格。但它的查询非常慢。
表用户
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;
答案 0 :(得分:2)
尝试使用CREATE INDEX
为post.userid
,post.poster_id
,followtoid.followerid
和user.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;