SQL选择超过两行

时间:2010-01-09 02:13:43

标签: sql database select

如何在下表中选择具有-A和b-B(作为键值对)的所有对象?

类似的东西:

SELECT DISTINCT(OBJECT) 
  FROM MYTABLE 
 WHERE key = 'a' 
   AND value = 'A' 
   AND key = 'b' 
   AND value = 'B'

...结果为1和3。

我知道这个SQL语句不起作用,但我希望它能解释一下我想要做的事情。

抱歉弥漫的头衔。我根本不知道如何更好地描述问题。

object | key | value
---------------------
1   |  a  |   A
1   |  b  |   B
1   |  c  |   C
2   |  a  |   F
2   |  b  |   B
3   |  a  |   A
3   |  b  |   B
3   |  d  |   D

3 个答案:

答案 0 :(得分:4)

select * 
from mytable 
where (key = a and value = a)
or    (key = b and value = b)

select * 
from mytable 
where key = a and value = a
union
select * 
from mytable 
where key = b and value = b

或更一般地说

select * 
from mytable 
where key = value
and key in (a,b)

答案 1 :(得分:4)

我想你想要这种形式的东西:

SELECT a.object 
FROM mytable a, mytable b 
WHERE a.object = b.object 
  AND a.key = 'a' AND a.value = 'A'
  AND b.key = 'b' AND b.value = 'B'

答案 2 :(得分:1)

你甚至可以试试这个

declare @t table(object int, keys varchar(10), value varchar(10))
insert into @t 
    select 1,'a','A' union all  select 1,'b','B' union all
            select 1,'c','C' union all  
    select 2,'a','F' union all  select 2,'b','B' union all
    select 3,'a','A' union all  select 3,'b','B' union all
            select 3,'d','D'
--select * from @t 

<强>查询

select object from @t 
where keys = 'a' and value ='A' 
or  keys = 'b'  and value ='B' 
group by object 
having COUNT(object)>1

<强>输出:

object
1
3