2013-04-27 133 views
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查询选择所有帖子,而不仅仅是那些有注释的帖子,但此时此查询返回那些也有意见的行。三个表中的SQL查询选择

回答

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 
0
Select * From Posts P 
Left Join Comments C on P.post_id = C.post_id 
Join Categories CG CG.id = P.cat_id 
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