将两个查询合并为一个

时间:2013-09-08 19:38:11

标签: mysql sql

如何将这两个查询加入已加入的查询中?

SELECT *
FROM   post 
       LEFT JOIN post_plus 
              ON ( post.id = post_plus.news_id ) 
       where approve = 1 
ORDER  BY fixed DESC, 
          date DESC 
LIMIT  0, 7; 

SELECT c1.postid
FROM   post_category c1
       JOIN post_category c2
         ON c1.postid = c2.postid
WHERE  c1.categoryid IN ( 130, 3, 4, 5 )
       AND c2.categoryid = 73 

2 个答案:

答案 0 :(得分:1)

如果post有一个外键来链接post_category:

SELECT *
FROM post p
JOIN post_category pc
ON p.fk_post_category = pc.id
JOIN post_category pc2
ON pc.postid = pc2.postid
LEFT JOIN post_plus pp
          ON ( p.id = pp.news_id ) 
where approve = 1 
and pc.categoryid IN ( 130, 3, 4, 5 )
   AND pc2.categoryid = 73  
ORDER  BY fixed DESC, 
      date DESC 
LIMIT  0, 7; 

显然,您的结果仅限于第一个查询。如果帖子和帖子类别之间不存在关系,请发布您希望如何放置这些表格

答案 1 :(得分:-1)

您可以使用 union 简单地加入这些查询,如果两个查询结果都具有类似数据类型的类似列。

(SELECT *
FROM   post 
       LEFT JOIN post_plus 
              ON ( post.id = post_plus.news_id ) 
       where approve = 1 
ORDER  BY fixed DESC, 
          date DESC 
LIMIT  0, 7 )

UNION

(SELECT c1.postid
FROM   post_category c1
       JOIN post_category c2
         ON c1.postid = c2.postid
WHERE  c1.categoryid IN ( 130, 3, 4, 5 )
       AND c2.categoryid = 73); 

http://dev.mysql.com/doc/refman/5.0/en/union.html