php mysql left join where子句错误

时间:2011-06-04 22:32:35

标签: mysql join

使用以下表格

帖子

  • ID
  • POST_ID
  • USER_ID

评论

  • ID
  • POST_ID
  • COMMENT_ID
  • USER_ID
  • 删除

回复

  • ID
  • POST_ID
  • reply_id
  • USER_ID
  • 删除

我正在尝试从每个帖子获取每条评论和回复.post_id和post.user_id ='x'并且评论或回复不会被删除(0)

这是我试过的

SELECT *
FROM posts p
LEFT JOIN comments c ON p.id=c.post_id
LEFT JOIN replies r ON p.id=r.post_id
WHERE p.user_id=$user_id
&& c.deleted='0' && r.deleted='0'

哪个不起作用......

2 个答案:

答案 0 :(得分:1)

您需要将已删除的支票放入加入条款。这应该这样做:

SELECT *
FROM posts p
LEFT JOIN comments c ON c.post_id = p.post_id AND NOT c.deleted
LEFT JOIN replies r ON r.post_id = p.post_id AND NOT r.deleted
WHERE p.user_id = $user_id

注意:不确定c.post_id是否加入p.id或p.post_id - 根据需要改变on子句

答案 1 :(得分:0)

帖子可能有评论或没有评论。使用LEFT JOIN代替INNER JOIN

帖子可能有回复。在该加入中也使用LEFT JOIN代替INNER JOIN

当使用LEFT JOIN时,类似WHERE comments.deleted = 0的条件包含一个字段(来自LEFT JOIN中的右表(comments)),LEFT JOIN将被取消。因此,我们应该将此条件放在ON子句中,而不是WHERE

SELECT *
FROM posts p
  LEFT JOIN comments c
    ON p.post_id = c.post_id
    AND c.deleted = 0
  LEFT JOIN replies r
    ON p.post_id = r.post_id
    AND r.deleted = 0  
WHERE p.user_id = $user_id

更清楚地思考,上面将显示问题所描述的内容,但在例如4条评论和3条回复的情况下,将返回12行(3x4)。这可能不是想要的。以下第二次尝试没有这样的问题。

我在表格中看不到post.textcomment.textreply.text,但无论如何,您都会明白这一点。如果不合适,您可以删除3 text行。

  ( SELECT p.post_id     AS post_id 
         , 0             AS type
         , p.post_id     AS id
         , p.text        AS text
    FROM posts p
    WHERE p.user_id = $user_id
  )
UNION ALL
  ( SELECT p.post_id     AS post_id 
         , 1             AS type
         , c.comment_id  AS id
         , c.text        AS text
    FROM posts p
      JOIN comments c
        ON p.post_id = c.post_id
    WHERE p.user_id = $user_id
      AND c.deleted = 0
  )
UNION ALL
  ( SELECT p.post_id     AS post_id 
         , 2             AS type
         , r.reply_id    AS id
         , r.text        AS text
    FROM posts p
      JOIN replies r
        ON p.post_id = r.post_id
    WHERE p.user_id = $user_id
      AND r.deleted = 0
  )
ORDER BY post_id
       , post_type
       , id

0,1,2表示发帖,评论,回复。