2010-12-01 34 views
1

什麼是使用一對多方法在以下數據庫設計中查詢具有特定屬性的產品的適當方式?mySQL:查詢一對多的表嗎?

我想我應該做類似下面的東西: SELECT (*) FROM productProperties WHERE property = 'weight' AND value = '10'

但是如果我需要的產品,同時具有重量= 10 &顏色=在同一個查詢是藍色的?數據庫設計的

實施例:

表:產品

------------------------ 
id | name  | price 
------------------------ 
0  | myName | 100 
1  | myName2 | 200 

表:productProperties

------------------------------------------------ 
product | property  | Value 
------------------------------------------------ 
0  | weight  | 10 
1  | weight  | 20 
1  | color  | blue 

回答

3

如果我需要的產品有 這兩個重量= 10 &顏色=藍色在 同樣的查詢?

一個選項:

select product, name 
    from products inner join productProperties 
    on (products.id = productProperties.product) 
where (property = 'weight' and value = '10') 
    or (property = 'color' and value = 'blue') 
group by product, name 
having count(1) = 2 

與子查詢的另一種選擇:

select id, name 
    from products p 
where exists (
     select 1 
      from productProperties pp1 
      where p.id = pp1.product 
      and pp1.property = 'weight' 
      and value = '10' 
     ) 
    and exists (
     select 1 
      from productProperties pp2 
      where p.id = pp2.product 
      and pp2.property = 'color' 
      and value = 'blue' 
     ) 
0
SELECT * FROM productProperties p 
WHERE (SELECT COUNT(*) FROM productProperties p1 WHERE p1.product = p.product AND 
((property = 'weight' AND value = '10') OR (property = 'color' AND value = 'blue')) 
=2