4

如果我有三个表:

posts
------
postid  date_posted title   content


views
------
viewid  post_id user_id


users
------
userid  username
  1. 列出所有posts未查看的正确方法是user_id什么?这个查询正确吗?
    SELECT * FROM posts LEFT JOIN views ON postid=post_id WHERE user_id=123 AND postid=NULL;

  2. 列出所有内容posts及其“查看状态”user_id怎么样?

  3. 您还可以推荐一个很棒的(用户友好的、非极客的)资源来提高我对 LEFT JOIN、CROSS JOIN 和(正常连接?从帖子、视图中选择 *)的理解吗?

谢谢!

4

5 回答 5

3

1.

SELECT *
FROM posts
WHERE postid NOT IN (
    SELECT post_id 
    FROM views
    WHERE user_id = 123
)

或者

SELECT *
FROM posts
LEFT JOIN views ON views.post_id = posts.postid AND views.user_id = 123
WHERE viewid IS NOT NULL
于 2012-09-26T09:31:57.513 回答
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
于 2012-09-26T09:34:44.807 回答
1

在回答您的第三个问题时,请检查来自 codinghorror.com 的 visual-explanation-of-sql-joins 的链接。这将帮助您增强对联接的理解。

于 2012-09-26T09:38:37.117 回答
0

1,您还需要包含 users 表,但这大致是正确的查询是的

2、SELECT * FROM posts LEFT JOIN views ON postid=post_id 应该显示它将显示所有帖子

3、http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

于 2012-09-26T09:34:13.897 回答
0

1)查看“scoota269”的回答

2) 查看您自己的 SQL 但删除AND postid=NULL

3) http://www.w3schools.com/sql/sql_join.asp

于 2012-09-26T09:34:25.113 回答