簡體   English   中英

MYSQL-選擇表A中的值,其中表B中的所有相應值都具有特定值

[英]MYSQL - Select values in table A where all the corresponding values in table B have a specific values

我有兩個表, 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規范,更少的冗余,更好的索引編制。

第一個查詢:

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(*))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM