2

假设我有一个包含许多评论的帖子表(并且评论属于用户)。

如何显示特定用户未发表评论的所有帖子?

假设我的数据库中有一个 ID 为 124 的用户;

select * from posts p left join comments c on p.id = c.post_id 
where c.id is null or c.user_id <> 124

但这似乎不对..如果帖子没有评论怎么办?

4

3 回答 3

1

您应该检查user_idfrom 表post而不是表comments,因为有些表user_id上还没有任何记录comments

SELECT  p.* 
FROM    posts p
        LEFT JOIN comments c
            ON p.id = c.post_id AND c.user_id = 124
WHERE   c.post_id IS NULL
于 2013-01-23T07:12:15.870 回答
0
select * from posts p left join comments c 
on p.id = c.post_id 
where c.post_id is null and p.user_id = 124;

编辑:

请试试这个:

SQLFIDDLE 演示

select * from posts p
where p.pid not in ( select c.pid
from comments c
where c.uid = 111)
;

| PID | PNAME |
---------------
|   3 |    p3 |
于 2013-01-23T07:12:58.897 回答
0

使用 null 作为您的问题的 id 是不好的做法我会使用这样的东西

select * from post p1 where not exists 
      (select 1 from comment c1 where c1.post_id = p1.id)
union
select * from post p2 where exists 
       (select 1 from comment c1 where c1.post_id = p1.id and c2.user_id <> 124)
于 2013-01-23T07:20:17.377 回答