1

我有两张桌子,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')

感谢您的帮助

4

2 回答 2

0

未经测试,但这应该可以工作:

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 规范,冗余更少,索引更好。

于 2012-11-13T10:48:41.813 回答
0

第一个查询:

SELECT *
FROM Orders
WHERE Exists (select null
              from ordered_products
              where
                orders.orders_id = ordered_products.orders_id
                and product_type=1)

第二个:

SELECT *
FROM Orders
WHERE
  Orders_id in (select orders_id
                from ordered_products
                where ordered_products.orders_id = orders.orders_id
                group by orders_id
                having sum(if(product_type=1,1,0))=count(*))
于 2012-11-13T10:49:55.273 回答