1
SELECT posts.id AS post_id, categories.id AS category_id, title, contents, posts.date_posted, categories.name, comments.id AS comment_id
FROM posts
LEFT JOIN (categories, comments) ON categories.id = posts.cat_id AND posts.id = comments.post_id
WHERE posts.id = 28

我希望这个 SQL 查询选择所有帖子,而不仅仅是那些有评论的帖子,但目前这个查询返回那些也有评论的行。

4

3 回答 3

0

试试这个:

SELECT 
    posts.id AS post_id,
    categories.id AS category_id, 
    title, contents, 
    posts.date_posted, 
    categories.name, 
    comments.id AS comment_id
FROM posts p, categories c, comments co
LEFT JOIN (categories, comments) ON categories.id = posts.cat_id AND posts.id = comments.post_id
WHERE p.cat_id = c.id 
and (co.post_id is null or co.post_id = p.id)
and posts.id = 28
于 2013-04-27T23:37:19.530 回答
0
Select * From Posts P
Left Join Comments C on P.post_id = C.post_id
Join Categories CG CG.id = P.cat_id
于 2013-04-27T23:44:05.337 回答
0

你认为这是什么意思?

LEFT JOIN (categories, comments) 
ON     categories.id = posts.cat_id 
       AND posts.id = comments.post_id

该文档建议逗号分隔的表列表等效于交叉连接:

LEFT JOIN 
        (
        categories
        cross join
        comments
        )
ON      categories.id = posts.cat_id 
        and comments.post_id = posts.id;

请注意,这将返回所有帖子,包括没有类别、没有评论或两者都没有的帖子。但如果没有评论,这将抑制类别,反之亦然。请参阅 SQL Fiddle 中的示例。

编写此代码的更好方法是在自己的联接中查找类别和评论:

LEFT JOIN 
        categories
ON      categories.id = posts.cat_id 
LEFT JOIN
        comments
ON      comments.post_id = posts.id

如果您只想要没有评论的帖子,请使用独占left join

LEFT JOIN
        comments
ON      comments.post_id = posts.id
...
WHERE   comments.id is null
于 2013-04-27T23:53:09.230 回答