sql查询-需要一些查询帮助吗

m1m5dgzv  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(396)

关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。

两年前关门了。
改进这个问题
我把er图附在下面。很简单。产品、产品类型、制造商及其关联。
查询需要做的是返回制造商的姓氏,以及他们生产的产品的产品名称,条件是这些制造商至少生产了两种不同类型的产品。
非常感谢您的回复。它们是非常有用和有教育意义的。我真的很感激。

8xiog9wr

8xiog9wr1#

没有任何数据很难查看,但这里有一个镜头。

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
n9vozmp4

n9vozmp42#

一种方法是在where子句中使用subselect来过滤select。我做得很快只是为了证明:

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
    )
gdx19jrr

gdx19jrr3#

灵感来自@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)

相关问题