mysql中的交集

时间:2010-11-12 12:26:16

标签: mysql

我的第一个查询

SELECT ID FROM wp_posts 
WHERE post_type = 'post' AND post_status = 'publish' 
AND ID IN (Select object_id FROM wp_term_relationships, wp_terms
           WHERE wp_term_relationships.term_taxonomy_id =18) 
ORDER BY post_date DESC

生成结果

 31 and 28

和我的第二个查询

SELECT ID FROM wp_posts 
WHERE post_type = 'post' AND post_status = 'publish' 
AND ID IN (Select object_id FROM wp_term_relationships, wp_terms 
           WHERE wp_term_relationships.term_taxonomy_id =8) 
ORDER BY post_date DESC

将产生

31 and 33

我只需要获得两个查询result.ie,31的交集。我们怎样才能使用mysql

4 个答案:

答案 0 :(得分:0)

一种简单的方法是:

SELECT FROM (that entire first query) WHERE ID IN (that entire second query)

我对它的效率没有任何承诺......

答案 1 :(得分:0)

交叉只不过是一个内连接,实际上是:

select
    a.ID as ID
from
    (SELECT ID FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' AND ID IN (Select object_id FROM wp_term_relationships, wp_terms WHERE wp_term_relationships.term_taxonomy_id =8 or wp_term_relationships.term_taxonomy_id =18)) as a,
    (SELECT ID FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' AND ID IN (Select object_id FROM wp_term_relationships, wp_terms WHERE wp_term_relationships.term_taxonomy_id =18 or wp_term_relationships.term_taxonomy_id =18)) as b
where
    a.ID=b.ID

从我的头顶。我只是复制&粘贴你的疑问,顺便说一句。

答案 2 :(得分:0)

您的查询不明确。 看看第二个查询。 你有以下

wp_term_relationships.term_taxonomy_id =18   OR
wp_term_relationships.term_taxonomy_id =18

答案 3 :(得分:0)

hmmm intersection - 尝试内连接:P