我有三个表,例如:
表
id(int) name(varchar) ref(int)
1 tissot 1234567
2 addidas 7654321
3 nike 8976543
属性表
id(int) name(varchar)
1 water_resistant
2 material_body
3 material_bracelet
4 watch_type
property_material 表
watch_id property_id value
1 1 200
1 2 steel
1 3 leather
1 4 quartz
2 1 50
2 2 plastic
2 3 leather
2 4 quartz
3 1 100
3 2 steel
3 3 rubber
3 4 mechanical
我想获得所有具有属性的手表,例如:
- 防水 >= 100
- material_body = 钢或塑料
- material_bracelet = 皮革或橡胶
- watch_type = 石英。
请帮我创建查询。属性可以约为 100。理想情况下,我希望得到结果:
watch_id name ref water_res mat_body mat_bracelet watch_type
1 tissot 1234 200 steel leather quartz
我正在尝试:
select
w.*, pm.value,pm.property_id
from
watch w
join
property_material pm
on w.id = pm.watch_id
where
pm.pid in (1,2,3)
and
pm.value in ('100','Steel','Leather');
但是此查询返回所有记录,例如,当值为 Steel 或 Leather 时,bur 我需要其中 material_body 是 Steel 而 material_bracelet 是 Leather。
更新:您对此查询有何看法?
select
name, ref
from
watch w
join
(SELECT w.id
FROM watch w
JOIN property_material pm on w.id = pm.watch_id
WHERE (pm.property_id = 1 AND pm.value > 100)
OR (pm.property_id = 2 AND pm.value IN ('steel','plastic'))
OR (pm.property_id = 3 AND pm.value IN ('leather','rubber'))
OR (pm.property_id = 4 AND pm.value = 'quartz')
Group by w.id
Having count(*) = 4) as t1
on t1.id = w.id;
最后更新:
select
w.name,
max(if(pm.property_id='1',pm.value,'')) water_resistant,
max(if(pm.property_id='2',pm.value,'')) material_body,
max(if(pm.property_id='3',pm.value,'')) material_bracelet,
max(if(pm.property_id='4',pm.value,'')) watch_type
from
watch w
join
(
SELECT w.id
FROM watch w
JOIN property_material pm on w.id = pm.watch_id
WHERE (pm.property_id = 1 AND pm.value > 100)
OR (pm.property_id = 2 AND pm.value IN ('steel','plastic'))
OR (pm.property_id = 3 AND pm.value IN ('leather','rubber'))
OR (pm.property_id = 4 AND pm.value = 'quartz')
Group by w.id
Having count(*) = 4
) as t1 on t1.id = w.id
join property_material pm on w.id = pm.watch_id
GROUP BY w.id