使用两个组合的MySQL查询

时间:2014-02-07 20:41:31

标签: php mysql sql mysqli

我有一个查询,我用来连接两个表(帖子,关系)来返回你关注的用户(r.status = 1)或朋友(r.status = 2)的帖子。但后来也省略了帖子隐私私密(p.privacy = 2)和当前关系(r.status = 1)的帖子。

这是我的问题:

$user_id= 1;

$posts_query= "
SELECT DISTINCT post_id, user_id, story, photo, link, collection_id, privacy, date, type
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)  
ORDER BY p.post_id DESC;
";

现在这个查询的唯一问题是它省略了你自己的个人帖子。

对此的查询是:

$your_posts_query= "SELECT * FROM posts WHERE user_id= '".$user_id."' ORDER BY p.post_id    
DESC";

现在,这不允许我将所有帖子聚合在一起。你的,以及你朋友和你所关注的人的那些。

我怎样才能使我的第一个查询也包含我的第二个查询所做的事情?

2 个答案:

答案 0 :(得分:0)

$user_id= 1;

$posts_query= "
SELECT DISTINCT post_id, user_id, story, photo, link, collection_id, privacy, date, type
FROM posts p
JOIN relations r ON p.user_id = r.recipient
AND (r.sender = '".$user_id."' OR p.user_id= '".$user_id."')
AND NOT (r.status = 1 AND p.privacy = 2)  
ORDER BY p.post_id DESC;
";

答案 1 :(得分:0)

将两者结合起来得到一个结果集

$posts_query= "
SELECT post_id, user_id, story, photo, link, collection_id, privacy, date, type  
FROM posts WHERE user_id= '".$user_id."' 
union 
SELECT DISTINCT post_id, user_id, story, photo, link, collection_id, privacy, date, type
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)  
ORDER BY p.post_id DESC;
";