只在一列上相交,返回其他列

时间:2014-09-06 19:05:08

标签: sql

我试图只在一列(map_id)上进行交集,但也返回另一列(attr):

SELECT map_id, attr 
FROM Attr
WHERE attr_id = 0 AND val = '123'
INTERSECT
SELECT map_id, attr
FROM Attr
WHERE attr_id = 20 AND val = '456' 

但是,如果map_id和attr对不匹配,则交集不起作用(显然)。如何在map_id上进行交集,但返回attrs列表?它最终成为较大查询的col In()子句的一部分。

例如:

---------------------------------
Attr_Id    Attr    Val    Map_Id
---------------------------------
0          '1'     '123'    1
0          '2'     '123'    2
10         '3'     '123'    1
10         '4'     '123'    2
20         '5'     '456'    1
20         '6'     '456'    2
30         '7'     '456'    1
30         '8'     '456'    2

我希望它返回

----------------
Attr_Id    Attr   
----------------
0          '1'   
20         '5'  

2 个答案:

答案 0 :(得分:1)

map_id具有这两个属性时,您似乎想要找到map_id的匹配属性。有不同的方法来处理此查询。这是一种方式:

select a.attr_id, a.attr
from Attr a
where (attr_id = 0 and val = '123' or
       attr_id = 20 and val = '456'
      ) and
      2 = (select count(distinct a2.attr_id)
           from attr a2
           where a2.map_id = a.map_id and
                (a2.attr_id = 0 and a2.val = '123' or
                 a2.attr_id = 20 and a2.val = '456'
                )
          )

答案 1 :(得分:0)

尝试:

select a.attr_id, a.attr
  from (select map_id
          from attr
         where attr_id = 0
           and val = '123'
        intersect
        select map_id
          from attr
         where attr_id = 20
           and val = '456') v
  join attr a
    on v.map_id = a.map_id

它返回每条记录的原因是因为您的2个查询都生成了MAP_ID值1和2.因此,将返回MAP_ID为1或2的表的每一行。这与您的预期输出不符,但符合您的解释。