2010-12-01 6 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

같은 제품이 필요한 경우 동일한 검색어에 weight = 10 & color = blue가 모두 필요합니까?

하나의 옵션 : 하위 쿼리와

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