我有'发布'和'评论'表。我想选择最后3个帖子和对该帖子的所有评论。我可以使用2个单独的语句:
SELECT p.* FROM post p ORDER BY p.date DESC LIMIT 3; // called 1
SELECT c.* FROM comment c WHERE c.post_id = :id; // called 3x time for each post.
可以将这些查询归为一个吗?
答案 0 :(得分:3)
您可以将子查询用于帖子集:
SELECT p.*
FROM (SELECT p.*
FROM post p
ORDER BY p.date DESC
LIMIT 3
) p JOIN
comment c
ON c.post_id = p.id
ORDER BY p.id, c.id;
答案 1 :(得分:1)
SELECT POST .*, COMMENT.*
from POST INNER JOIN COMMENT ON POST.id = COMMENT.post_id
where POST.id = COMMENT.post_id ORDER BY POST.id LIMIT 3
答案 2 :(得分:1)
你也可以尝试这个
SELECT p . * , c . *
FROM post p
LEFT JOIN
COMMENT c ON c.post_id = p.id
where p.id IN (SELECT id from post order by date desc limit 3) ORDER BY p.date