2016-09-30 15 views
0

很少有數據庫表像order_productsreturn_productsSQL查詢修改,以獲得實際收益的產品數量

return_products表列: idrma_idorder_idproduct_idorder_nrcommentadmin_commentadd_date

order_products表列: id,order_id,product_id, quantity, price, sum

產品回報每行每一個產品,但order_products,擁有數量列

和現在有這樣的SQL查詢得到這取決於什麼樣的產品搜索訂單:

SELECT `id`, `saved` 
FROM `orders` 
WHERE 1 AND (`id` IN(
    SELECT `order_id` 
    FROM `order_products` 
    WHERE `product_id` IN (1,2,3,4,5))) 
BY id DESC 
LIMIT 0, 30 

,現在需要檢查訂單和產品ID是否在退貨和退貨產品表

即 如果在id中搜索產品我需要檢查該產品是否exi如果計數等於order_products數量,則不需要在列表中顯示該訂單,但是如果退貨數量少於order_products數量則需要顯示(order_products.quantity - COUNT(return_products))

+0

請提供樣本數據。什麼是退貨表,哪一個return_products.order_id或order_nr是指銷售訂單? – Serg

回答

0

那裏沒有與訂單表的關係,但是您具有order_products/return_products數量比較的邏輯。

select op.product_id, op.quantity, count(rp.id) 
from order_products op 
left join return_products rp on rp.product_id = op.product_id --maybe need to join on order_id too ? Not really clear 
group by op.product_id, op.quantity 
--where op.product_id in (1, 2, 3, 4, 5) 
having op.quantity <> count(rp.id)