2012-04-12 54 views
1

分組我的搜索詞我很抱歉,如果標題是混亂的,它是更好的例子來說明SQL返回行ID。如果一個字段匹配由我行ID

我有一個表的數據是這樣的:

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

我想過去的搜索詞,例如,「俗氣」和「多汁」。這應返回:

ProductA 

...因爲產品A id爲1和3

但是如果我搜索「俗氣」和「苦」,這應該返回任何記錄爲產品A可能有'匹配Cheesy「,但它不包含'苦'的記錄。

這可能嗎?

+0

您是否嘗試過在你的查詢中使用'INTERSECT'? – HABO 2012-04-12 16:34:41

+0

@ user92546:好一點,爲什麼不公佈答案? – Andomar 2012-04-12 16:39:18

+0

@Andomar - 解決下方的關注。有時用戶願意提供他們所嘗試的一些概念。有時在生產方向上微調就足夠了。其他時候,他們只想要血腥的答案!所以就這樣了。 – HABO 2012-04-12 16:43:20

回答

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' 

編輯:其他例子:

-- 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

嗨,謝謝你。我也做了以下內容: 選取產品 從產品 WHERE(屬性=「俗氣」) INTERSECT 選取產品 從產品 WHERE(屬性=「多汁的」) 你能告訴我爲什麼,當我代替做一個「SELECT *」,這不起作用? – RiceBucket 2012-04-12 17:29:40

+0

根據[MSDN](http://msdn.microsoft.com/en-us/library/ms188055(V = SQL.105)的.aspx)'INTERSECT'意味着'DISTINCT'值。當您選擇其他列時,值是不同的,交叉點是空的。我會編輯我的答案以提供另一個例子。 – HABO 2012-04-12 17:52:04

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

東西沿着這些線路可以工作過,我想。

相關問題