我附上了ER图。这很简单。产品,产品类型,制造商及其协会。
查询需要做的是返回制造商的姓氏,以及他们生产的产品的产品名称,条件是这些制造商生产了至少两种不同类型的产品。
非常感谢回复。他们非常有用和有教育意义。我真的很感激。
答案 0 :(得分:0)
这样做的一种方法是使用where子句中的子选择来过滤您的选择。我这样做的速度非常快,只是为了证明:
select * from manufacturer m
inner join manufacturer_has_product mhp
on m.manufacturer_id = m.manufacturer_id
inner join product p
on mhp.product_id = p.product_id
where m.manufacturer_id in (
select m.manufacturer_id
from manufacturer m
inner join manufacturer_has_product mhp
on m.manufacturer_id = m.manufacturer_id
inner join product p
on mhp.product_id = p.product_id
inner join productType_has_product pthp
on pt.product_product_id = p.product_id
inner join productType pt
on pt.productType_type_id = pt.type_id
group by m.manufacturer_id
having count(pt.type_id) > 1
)
答案 1 :(得分:0)
很难看到没有任何数据,但这是一个镜头。
select p.Name, m.last_name from Product p
inner join manufacturer m on m.manufacturer_id = p.product_id
inner join productType pT on p.product_id = pT.type_id
where COUNT(distinct pT.type_id) >= 2
group by m.manufacturer_id
答案 2 :(得分:0)
灵感来自@ Eric的答案,未经过测试,评论中的解释......
SELECT tmp.last_name, p.name -- <- compose the final select
FROM
-- sub-select the underlying manufacturers (id + last_name):
(
-- distinct ... or join deeper
SELECT COUNT (DISTINCT php.productType_type_id), m.manufacturer_id, m.last_name
FROM manufacturer m
JOIN manufacturer_has_product mhp
ON (mhp.manufacturer_manufacturer_id = m.manufacturer_id)
JOIN Product p
ON (p.product_id = mhp.Product_product_id)
--- until "php" is enough, but needs distinct
JOIN productType_has_product php
ON (php.Product_product_id = p.product_id)
-- obligatory:
GROUP BY m.manufacturer_id, m.last_name
-- (aggregated) filter condition:
HAVING COUNT (DISTINCT php.productType_type_id) > 1
) tmp -- an alias for the sub-select
-- join for the final result:
JOIN manufacturer_has_product mhp
-- on TMP.manufacturer_id!
ON (mhp.manufacturer_manufacturer_id = tmp.manufacturer_id)
JOIN Product p ON (p.product_id = mhp.Product_product_id)