MYSQL - 选择表 A 中的值,其中表 B 中的所有对应值都具有特定值

标签 mysql join

我有两个表,ordersordered_products

ORDERS
|ORDERS_ID|CUSTOMER NAME|...
|1        |PIPPO        |...
|2        |PLUTO        |...

ORDERED PRODUCTS
|ORDERED_ID|ORDERS_ID|PRODUCT  |PRODUCT_TYPE|...
|1         |1        |ProdottoA| 1          |...
|2         |1        |ProdottoB| 2          |...
|3         |1        |ProdottoC| 1          |...
|4         |2        |ProdottoD| 2          |...

我需要两个查询,第一个选择具有至少一种类型 1 产品的所有订单,第二个选择具有类型 1 的所有产品的所有订单。

对于第一个我用下面的查询解决了:

select distinct orders_id from ORDERS o left join ORDERED_PRODUCTS op on (o.orders_id=op.orders_id) where op.product_type = '1'

但是我找不到第二个查询的解决方案。


已找到解决方案!我用过:

select distinct orders_id from ORDERS o left join ORDERED_PRODUCTS op on (o.orders_id=op.orders_id) 
where
(select count(ordered_id) from ordered_products op where op.orders_id = o.orders_id)
=
(select count(ordered_id) from ordered_products op where op.orders_id = o.orders_id and op.orders_products_categorizzazione='1')

谢谢你的帮助

最佳答案

未测试,但这应该有效:

select orders_id
from orders
where 
  ( 
  select count(distinct product)
    from ordered_products
    where ordered_products.orders_id = orders.orders_id
    and ordered_products.product_type = 1
  )
  =
  (
  select count(distinct product)
    from ordered_products
    where ordered_products.product_type = 1
  );

它的作用:

  • 统计当前订单中类型 1 的所有不同产品
  • 计算所有订单中类型 1 的所有不同产品
  • 比较结果

它远未优化,可能有更好的方法,但它确实有效并且易于理解。

PS:如果您可以选择数据库结构,我会选择为产品本身准备一个不同的表。更符合 UML 规范,冗余更少,索引更好。

关于MYSQL - 选择表 A 中的值,其中表 B 中的所有对应值都具有特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13359101/

相关文章:

mysql - 快速查询选择不在 MySQL 中另一个表中的所有记录

mysql - 获取日期和 null 之间的数据

MySQL连接查询使用like?

mysql - sql数据库,有多个where,second max

mysql - 使用 Active Record 区分大小写的数据库搜索

mysql - 我可以使用 MySQL 触发器更新刚刚添加的行吗

mysql - 看似简单的MYSQL查询

MySQL : Create view JOIN get max and min value from child table

MySQL:如何删除基于列的多行记录中的一行

mysql - 关联同一个表中的两列