2

如何将这两个查询合并为一个已经加入的查询?

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 
4

2 回答 2

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; 

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

于 2013-09-08T19:44:39.587 回答
-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

于 2013-09-08T19:47:35.257 回答