이러한 종류의 테이블은 종종 키/값 저장소라고합니다. 확장 가능한 속성 목록을 처리하는 올바른 방법이지만 사용할 때 약간의 번거 로움이 될 수 있습니다.
이렇게 쿼리하면 product_id
값이 기준 목록과 일치하는 순서대로 표시됩니다. 가장 일치하는 값이 먼저옵니다. (http://sqlfiddle.com/#!9/7870b5/2/0)
select count(*) matches, product_id
from prop
where property in ('tshirt','medium')
group by product_id
order by 1 desc
이 조회하지만, 크기, 색상, 유형의 차이 무지.
크기, 색상 등을 정확하게 일치 시키려면 좀 더 복잡해집니다. 키/값 속성 테이블을 피벗하는 쿼리로 시작해야합니다. 행을 열로 바꿉니다. (http://sqlfiddle.com/#!9/7870b5/3/0)
select id.product_id,
color.property color,
type.property type,
size.property size
from (select distinct product_id from prop) id
left join prop color on id.product_id = color.product_id and color.property_name = 'color'
left join prop type on id.product_id = type.product_id and type.property_name = 'type'
left join prop size on id.product_id = size.product_id and size.property_name = 'size'
당신은 아마도과 같이, 가상 테이블로이를 치료하고 쿼리해야합니다. (http://sqlfiddle.com/#!9/7870b5/4/0)
select *
from (
select id.product_id,
color.property color,
type.property type,
size.property size
from (select distinct product_id from prop) id
left join prop color on id.product_id = color.product_id and color.property_name = 'color'
left join prop type on id.product_id = type.product_id and type.property_name = 'type'
left join prop size on id.product_id = size.product_id and size.property_name = 'size'
) allprops
where size='medium' and color = 'blue'
많은 개발자와 DBA이 조금 더 쉽게 만드는 allprops
같은보기를보고 뭔가를 만들 것입니다.
을보십시오. 각 특성 이름은 특성 항목에 따라 다른 필드 여야합니다. – apomene