查询选择现有密钥

时间:2011-11-28 17:02:00

标签: sql sql-server sql-server-2008

我有一张包含以下数据的表

key     code
============
key1    220
key1    221
key2    220
key2    221
key2    222
key3    220
key4    255
key5    220
key5    221

密钥和代码的组合不能在表中重复(2列用作复合主键)。 我想要一个查询,它将为给定的一组代码选择匹配的密钥,例如对于代码220,221,预期结果将是key1和key 5,因为只有这些匹配这些代码集。

4 个答案:

答案 0 :(得分:2)

你在找这样的东西吗?

DECLARE @Test TABLE (TblKey CHAR(4), code INT)

INSERT INTO @test VALUES('key1', 220),('key1', 221),('key2', 220),('key2', 221),
                        ('key2', 222),('key3', 220),('key3', 220),
                        ('key4', 255),('key5', 220), ('key5', 221)

SELECT TblKey FROM @Test WHERE Code = 220
INTERSECT
SELECT TblKey FROM @Test WHERE Code = 221

当我运行它时,我得到key1, key2, key5的输出 - 所有这些输出都有一个样本中包含值220和221的条目。

答案 1 :(得分:2)

将您要查找的值插入表变量@Match,并在针对您的表@T的查询中使用它。

declare @T table
(
  [key] char(4),
  code int,
  primary key([key], code)
)

insert into @T values
('key1',    220),
('key1',    221),
('key2',    220),
('key2',    221),
('key2',    222),
('key3',    220),
('key3',    333),
('key4',    255),
('key5',    220),
('key5',    221)

declare @Match table (code int)
insert into @Match values (220),(221)

select T.[key]
from @T as T
  left outer join @Match as M
    on T.code = M.code
group by T.[key]
having count(*) = (select count(*) from @Match) and
       count(M.code) = (select count(*) from @Match)

http://data.stackexchange.com/stackoverflow/q/119432/

答案 2 :(得分:1)

只是在桌子上抛出另一个选项:

declare @KeyCode Table
(
    [Key] nvarchar(10),
    Code nvarchar(10)
)

insert into @KeyCode values('key1',    220)
insert into @KeyCode values('key1',    221)
insert into @KeyCode values('key2',    220)
insert into @KeyCode values('key2',    221)
insert into @KeyCode values('key2',    222)
insert into @KeyCode values('key3',    220)
insert into @KeyCode values('key3',    220)
insert into @KeyCode values('key4',    255)
insert into @KeyCode values('key5',    220)
insert into @KeyCode values('key5',    221)

select [Key]
from @KeyCode
where Code = 220

intersect

select [Key]
from @KeyCode
where Code = 221

except 

select [Key]
from @KeyCode
where Code not in (220,221)

返回key1和key5。

Working example.

答案 3 :(得分:0)

你的意思是这样吗?

SELECT key 
FROM tblKeyCodes 
where code in (220,221)