我们可以在没有子查询的情况下进行此查询吗?
SELECT login, post_n,
(SELECT SUM(vote) FROM votes WHERE votes.post_n=posts.post_n)AS votes,
(SELECT COUNT(comments.post_n) FROM comments WHERE comments.post_n=posts.post_n)AS comments_count
FROM users, posts
WHERE posts.id=users.id AND (visibility=2 OR visibility=3)
ORDER BY date DESC LIMIT 0, 15
表:
用户:id,login
帖子:post_n,id,visibility
投票:post_n,投票
id - 它是用户ID,用户是主表。
答案 0 :(得分:2)
是的,有可能:
SELECT login, post_n,
SUM(vote) as votes,
FROM users
JOIN posts using(id)
LEFT JOIN votes using(post_n)
WHERE visibility=2 OR visibility=3
GROUP BY login, post_n
然后压扁结果:
select * from
(
SELECT login, post_n,
SUM(vote) as votes,
FROM users
LEFT JOIN posts using(id)
LEFT JOIN votes using(post_n)
WHERE visibility=2 OR visibility=3
GROUP BY login, post_n
) as votes_count
然后加入评论:
select votes_count.login, votes_count.post_n, votes_count.votes,
COUNT(comments.post_n) as comments_count
from
(
SELECT login, post_n,
SUM(vote) as votes,
FROM users
LEFT JOIN posts using(id)
LEFT JOIN votes using(post_n)
WHERE visibility=2 OR visibility=3
GROUP BY login, post_n
) as votes_count
LEFT JOIN comments using(post_n)
GROUP BY votes_count.login, votes_count.post_n
ORDER BY date DESC LIMIT 0, 15
答案 1 :(得分:0)
您可以在“用户”表格中存储投票金额和帖子计数,并通过触发器或“更新”查询进行更新。
答案 2 :(得分:0)
我在使用join或在哪里合并表时测试了变体和测试变体。
没有子查询变量更慢,0.0208秒,而mysql在投票表中仅使用271行,但是当我使用连接时,它使用整行。这里没有子查询变体:
SELECT res.*, COUNT(*) FROM
(
SELECT login, posts.post_n, SUM(vote)AS votes
FROM users, posts, votes
WHERE users.id=posts.id AND posts.post_n=votes.post_n AND visibility=3
GROUP BY posts.post_n
)AS res, comments
WHERE comments.post_n=res.post_n
GROUP BY res.post_n
ORDER BY date DESC
LIMIT 0, 15
子查询varian仅执行0.0027秒,它没有缓存,但在所有测试中都使用了索引。
P.S。对不起我的英文