2012-04-12 7 views
1

タイトルが混乱しているのはごめん。SQL返された行IDが、行IDでグループ化された検索語句と一致する場合

私はこのようなデータのテーブルを持っている:

1 ProductA 'Cheesy' 
2 ProductA 'Creamy' 
3 ProductA 'Juicy' 
4 ProductB 'Buttery' 
5 ProductB 'Clean' 
6 ProductC 'Bitter' 

私は検索語の過去、例えば、「安っぽい」と「ジューシー」にしたいです。これは返す必要があります:

ProductA 

... ProductAは、ID 1と3

と一致した。しかし、私は「安っぽい」と「ビター」を検索すると、これは「ProductAが有してもよいようにレコードを返さないはずですので、 Cheesy 'だが、Bitterのレコードは入っていない。

これは可能ですか?

+0

あなたの質問に「INTERSECT」を使ってみましたか? – HABO

+0

@ user92546:良い点、なぜあなたは答えを投稿しないのですか? – Andomar

+0

@Andomar - 以下にあなたの懸念を解決しました。ユーザーは、試みたことの何らかの概念を提供したいと思うことがあります。時には、生産的な方向のナッジで十分です。他の時間彼らは今すぐ血のある答えをしたい!だからそうなるのです。 – HABO

答えて

2

一つのアプローチ:

declare @Products as Table (ProductId Int Identity, Product VarChar(16), Property VarChar(16)) 
insert into @Products (Product, Property) values 
    ('ProductA', 'Cheesy'), ('ProductA', 'Creamy'), ('ProductA', 'Juicy'), 
    ('ProductB', 'Buttery'), ('ProductB', 'Clean'), 
    ('ProductC', 'Bitter') 

select Product 
    from @Products 
    where Property = 'Cheesy' 
intersect 
select Product 
    from @Products 
    where Property = 'Juicy' 

EDIT:追加例:これらの線に沿って

-- To retrieve all data for the matching product(s):  
select * 
    from @Products 
    where Product in (
    select Product 
     from @Products 
     where Property = 'Cheesy' 
    intersect 
    select Product 
     from @Products 
     where Property = 'Juicy') 
+0

こんにちは、ありがとう。私は、次のことを行っている: SELECT製品 を生成物から、 WHERE(プロパティ= '安っぽい')を INTERSECT SELECT製品 を生成物から、 WHERE(プロパティ= 'ジューシー')を あなたはなぜ私を伝えることができ、時に代わりにI "SELECT *"を実行しますが、これは機能しませんか? – RiceBucket

+0

[MSDN](http://msdn.microsoft.com/en-us/library/ms188055(v = sql.105).aspx)によると、「INTERSECT」は、「DISTINCT」値を意味します。追加の列を選択すると、値が異なり、交差が空になります。私は別の例を提供するために私の答えを編集します。 – HABO

1
select product from products 
where property = 'Cheesy' -- property 1 
or 
property = 'Juicy' -- property 2 
group by product 
having count(*) >= 2 -- number of properties 

何かがあまりにも仕事ができる、私は思います。

関連する問題