2012-11-13 43 views
1

我有兩個表,ordersordered_productsMYSQL - 選擇表A中的值,其中表B中的所有對應值都具有特定值

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

感謝您的幫助

回答

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規範更適合,冗餘度更低,索引更好。

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(*)) 
相關問題