【发布时间】:2014-02-09 19:35:43
【问题描述】:
我有两个表“posts”和“relations”
为了简洁起见,我从表格中省略了非必要的列。
“帖子”
post_id | user_id | privacy
“关系”
rel_id | sender | recipient | status
这是我想要完成的:
抓取posts表中user_id=relationship表中的receiver的所有post,并跳过relationship表中status为1、postprivacy为2的post。
现在,我还想同时从 user_id = $user_id 的用户表中获取所有帖子
我尝试在查询中使用带有 OR 语句的连接。它不能正常工作。我认为问题在于我在我的加入中设置 p.user_id = r.recipient 并且用户的 id 唯一出现在收件人列中的时候是 SOMEONE ELSE 是否关注(status = 1)或朋友(status = 2 ) 与当前用户。
我当前的 MySQL 查询:
SELECT DISTINCT post_id, user_id, privacy
FROM posts p
JOIN relations r ON p.user_id = r.recipient
AND (r.sender = '".$user_id."')
AND NOT (r.status = 1 AND p.privacy = 2)
OR (p.post_id = '".$user_id."')
ORDER BY p.post_id DESC
所以我认为我需要使用 UNION 但它根本不起作用。我试过了:
SELECT * FROM posts WHERE user_id = '".$user_id."'
UNION
SELECT *
FROM posts p
JOIN relations r ON p.user_id = r.recipient
AND (r.sender = 1)
AND NOT (r.status = 1 AND p.privacy = 2)
ORDER BY p.post_id DESC
我做错了什么?
【问题讨论】: