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

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

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

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

8xiog9wr

8xiog9wr1#

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

  1. select p.Name, m.last_name from Product p
  2. inner join manufacturer m on m.manufacturer_id = p.product_id
  3. inner join productType pT on p.product_id = pT.type_id
  4. where COUNT(distinct pT.type_id) >= 2
  5. group by m.manufacturer_id
n9vozmp4

n9vozmp42#

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

  1. select * from manufacturer m
  2. inner join manufacturer_has_product mhp
  3. on m.manufacturer_id = m.manufacturer_id
  4. inner join product p
  5. on mhp.product_id = p.product_id
  6. where m.manufacturer_id in (
  7. select m.manufacturer_id
  8. from manufacturer m
  9. inner join manufacturer_has_product mhp
  10. on m.manufacturer_id = m.manufacturer_id
  11. inner join product p
  12. on mhp.product_id = p.product_id
  13. inner join productType_has_product pthp
  14. on pt.product_product_id = p.product_id
  15. inner join productType pt
  16. on pt.productType_type_id = pt.type_id
  17. group by m.manufacturer_id
  18. having count(pt.type_id) > 1
  19. )
展开查看全部
gdx19jrr

gdx19jrr3#

灵感来自@eric的答案,未经测试,评论中的解释。。。

  1. SELECT tmp.last_name, p.name -- <- compose the final select
  2. FROM
  3. -- sub-select the underlying manufacturers (id + last_name):
  4. (
  5. -- distinct ... or join deeper
  6. SELECT COUNT (DISTINCT php.productType_type_id), m.manufacturer_id, m.last_name
  7. FROM manufacturer m
  8. JOIN manufacturer_has_product mhp
  9. ON (mhp.manufacturer_manufacturer_id = m.manufacturer_id)
  10. JOIN Product p
  11. ON (p.product_id = mhp.Product_product_id)
  12. --- until "php" is enough, but needs distinct
  13. JOIN productType_has_product php
  14. ON (php.Product_product_id = p.product_id)
  15. -- obligatory:
  16. GROUP BY m.manufacturer_id, m.last_name
  17. -- (aggregated) filter condition:
  18. HAVING COUNT (DISTINCT php.productType_type_id) > 1
  19. ) tmp -- an alias for the sub-select
  20. -- join for the final result:
  21. JOIN manufacturer_has_product mhp
  22. -- on TMP.manufacturer_id!
  23. ON (mhp.manufacturer_manufacturer_id = tmp.manufacturer_id)
  24. JOIN Product p ON (p.product_id = mhp.Product_product_id)
展开查看全部

相关问题