1

如果标题令人困惑,我很抱歉,最好在示例中进行解释。

我有一个这样的数据表:

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

我想添加一个搜索词,例如“Cheesy”和“Juicy”。这应该返回:

ProductA

...因为 ProductA 与 id 1 和 3 匹配。

但是,如果我搜索“Cheesy”和“Bitter”,这应该不会返回任何记录,因为 ProductA 可能有“Cheesy”,但它不包含“Bitter”的记录。

这可能吗?

4

2 回答 2

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' )
于 2012-04-12T16:39:31.420 回答
1
select product from products 
where property = 'Cheesy' -- property 1
or 
property = 'Juicy' -- property 2
group by product
having count(*) >= 2 -- number of properties

Something along these lines could work too, I think.

于 2012-04-12T16:52:15.163 回答