如果我有三张桌子:
posts
------
postid date_posted title content
views
------
viewid post_id user_id
users
------
userid username
列出posts
尚未查看的所有user_id
的正确方法是什么?这个查询是否正确?
SELECT * FROM posts LEFT JOIN views ON postid=post_id WHERE user_id=123 AND postid=NULL;
如何列出所有posts
及其"查看状态"按user_id
?
您是否也可以推荐一个优秀的(用户友好的,非geeky)资源来提高我对LEFT JOIN,CROSS JOIN和(正常联接?从帖子,视图中选择*)的理解?
谢谢!
答案 0 :(得分:3)
1
SELECT *
FROM posts
WHERE postid NOT IN (
SELECT post_id
FROM views
WHERE user_id = 123
)
OR
SELECT *
FROM posts
LEFT JOIN views ON views.post_id = posts.postid AND views.user_id = 123
WHERE viewid IS NOT NULL
答案 1 :(得分:1)
1.select * from posts where post_id in(select post_id from views where user_id<>123)
or
select * from posts p join views v
on p.post_id=v.post_id
and v.user_id<>123
2.select p.*,CASE when isnull(v.viewid,0)=0 then 0 else 1 end as viewstatus
from posts p left join views v
on p.post_id=v.post_id
答案 2 :(得分:1)
在回答您的第3个问题时,请查看visual-explanation-of-sql-joins from codinghorror.com中的链接。这可以帮助您增强连接的基础。
答案 3 :(得分:0)
1,您还需要包含users表,但这大致是正确的查询是
2,SELECT * FROM发布LEFT JOIN视图ON postid = post_id应显示它将显示所有帖子
3,http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
答案 4 :(得分:0)