我有几张表:型号、产品、规格、图片和商店。
它们的关联如下:
每个产品属于(型号,商店)
每个图片属于(产品)
每个规格属于(产品)
我需要一份产品清单,
与他们所属的商店(按product.store_id)
,其中product.model_id=some_id
仅当产品有规格时(按spec.product_id)仅当产品有图片时(按picture.product_id)
我需要什么类型的查询?
谢谢
您的定义非常完整,可以直译为:
select
-- Selecting all fields of product and store.
-- You can refine this by only listing the fields you need.
p.*,
s.*
from
-- need a list of products,
product p
-- with the store they belongs to (by product.store_id)
inner join store s on s.store_id = p.store_id
where
-- ONLY if there are specs for the product (by spec.product_id)
exists
(select
'x'
from
spec ps
where
ps.product_id = p.product_id) and
-- ONLY if a product has pictures (by picture.product_id)
exists
(select
'x'
from
pictures pp
where
pp.product_id = p.product_id)
试试这个::
Select * from
from
product p
inner join model m on (p.model_id=m.id)
inner join store s on (p.store_id=s.id)
inner join picture pc on (p.picture_id=pc.id)
inner join spec sp on (p.spec_id=sp_id)
where product.model_id=some_id
GROUP BY product.id