如何组合2个复杂的mysql查询

时间:2014-10-11 07:58:26

标签: php mysql

所以我有两个MySQL查询,如果我知道要结合我会,但我不会这样,为什么我转向" SO",在那种情况下我没有尝试任何东西,因为它超出了我的范围。我希望将所有问题合并在一起,如果不可能,请告诉我。

查询一个"这将选择您的所有朋友帖子,包括您的帖子":

"SELECT b.*, c.photo, d.name, e.status 
FROM post b 
INNER JOIN profile c 
INNER JOIN user d 
INNER JOIN user_friendship e 
ON b.from_user = c.user_id 
AND b.from_user = d.id 
AND e.friend_id = b.from_user 
WHERE e.status = :status 
AND e.user_id = :id
ORDER BY b.id DESC LIMIT 20"

查询二"这会选择以下帖子的所有人":

"SELECT b.*, c.photo, d.name, e.status
FROM post b
INNER JOIN profile c 
INNER JOIN user d 
INNER JOIN user_follower e 
ON b.from_user = c.user_id 
AND b.from_user = d.id 
AND e.to_id = b.from_user 
WHERE e.status = :status 
AND e.who_id = :id
ORDER BY b.id DESC LIMIT 20"

我已将这些结合起来,但仅限于php。我想在一个MySQL查询中结合使用。提前致谢

2 个答案:

答案 0 :(得分:2)

SELECT *
FROM
  (SELECT b.*,
          c.photo,
          d.name,
          e.status
   FROM post b
   INNER JOIN profile c
   INNER JOIN USER d
   INNER JOIN user_friendship e ON b.from_user = c.user_id
   AND b.from_user = d.id
   AND e.friend_id = b.from_user
   WHERE e.status = :status
     AND e.user_id = :id LIMIT 20
   UNION SELECT b.*,
                c.photo,
                d.name,
                e.status
   FROM post b
   INNER JOIN profile c
   INNER JOIN USER d
   INNER JOIN user_follower e ON b.from_user = c.user_id
   AND b.from_user = d.id
   AND e.to_id = b.from_user
   WHERE e.status = :status
     AND e.who_id = :id LIMIT 20 ) MainQuery
ORDER BY id DESC

答案 1 :(得分:2)

SELECT b.*, c.photo, d.name, e.status, "P" 
FROM post b 
INNER JOIN profile c 
INNER JOIN user d 
INNER JOIN user_friendship e 
ON b.from_user = c.user_id 
AND b.from_user = d.id 
AND e.friend_id = b.from_user 
WHERE e.status = :status 
AND e.user_id = :id
ORDER BY b.id DESC LIMIT 20
UNION
SELECT b.*, c.photo, d.name, e.status, "F"
FROM post b
INNER JOIN profile c 
INNER JOIN user d 
INNER JOIN user_follower e 
ON b.from_user = c.user_id 
AND b.from_user = d.id 
AND e.to_id = b.from_user 
WHERE e.status = :status 
AND e.who_id = :id
ORDER BY b.id DESC LIMIT 20

使用额外的列,您可以看到行的来源(P = post,F = follow)

请记住,union将删除重复的行。如果您想查看所有行,请使用UNION ALL