来自三个表的SQL Query SELECT

时间:2013-04-27 23:34:28

标签: sql mysqli

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查询选择所有帖子,而不仅仅是那些有评论的帖子,但此时此查询还会返回那些也有评论的行。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

Select * From Posts P
Left Join Comments C on P.post_id = C.post_id
Join Categories CG CG.id = P.cat_id

答案 2 :(得分:0)

您认为这意味着什么?

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

The documentation suggests逗号分隔的表格列表相当于交叉连接:

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

请注意,这将返回所有帖子,包括没有类别,没有评论或没有评论的帖子。但如果没有评论,这将取消该类别,反之亦然。 See example at 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