Mysql查询满足多个类别的产品列表

版权声明:随意转载。 https://blog.csdn.net/Hynial/article/details/50582896

问题:

像淘宝中搜索满足多个条件的产品列表

举例:

有个产品表product_page:

id 产品字段...
1 产品字段内容...
2 产品字段内容...

有个产品类别表property_page:(其中,a、b属于1类,c、d属于2类,e、f属于3类)

id type typeinstance
1 1 a
2 1 b
3 2 c
4 2 d
5 3 e
6 3 f

产品与类别关系表product_property:(其中,product_id是product_page的id,property_id是property_page的id)

id product_id property_id
1 1 1
2 2 1
3 1 4
4 4 2
5 1 5

问题1,查询所有带有1类中的a属性的产品:

SQL查询:(先查询a属性的类别id是1)

SELECT * FROM product_page where id in 
(
	select p.product_id from product_property p where p.property_id=1
) 

问题2,查询所有同时满足属于a属性和d属性的产品:

SQL查询:(先查询a属性的类别id是1,c属性的类别id是3)

SELECT * FROM product_page where id in 
(
		select p.product_id from (
			product_property p,
			(select product_id,property_id from product_property) p2 
		) where p.property_id=1 and p2.property_id=3 and  p.product_id=p2.product_id
)

问题3,查询所有同时满足属于a属性和d属性和e属性的产品:

SQL查询:(先查询a属性的类别id是1,c属性的类别id是3,e属性的类别id是5)

SELECT * FROM product_page where id in 
(
	select p.product_id from 
	(
			product_property p,
			(select product_id,property_id from product_property) p2,
			(select product_id,property_id from product_property) p3 
	)
	where p.property_id=1 and p2.property_id=3 and p3.property_id=5 and 
	p.product_id=p2.product_id and 
	p2.product_id=p3.product_id
)

示例图片:




猜你喜欢

转载自blog.csdn.net/Hynial/article/details/50582896