例如:我有4个表: 表1:项目
item_id name quantity
==========================
1 a 10
2 b 15
表2:附加
add_id name quantity item_id
===================================
1 c 5 1
表3:item_out(这将减去项目数量)
item_id quantity
==========================
1 10
2 5
表4:additional_out(这将减去额外的数量)
additional_id quantity
==========================
1 5
我的问题是:为了获得这些结果,我应该给出什么样的mysql查询?
item_ id quantity additional_id additinal_quantity
=================================================
1 5 1 0
2 15
因为我使用mysql查询代码,如:
SELECT item_id, SUM(quantity - IFNULL(number,0)), additional_id, SUM(additional_quantity - IFNULL(additional_number,0))
FROM(
SELECT a.item_id, a.quantity, b.additional_id, b.quantity AS additional_quantity, NULL AS number, NULL AS additional_number
FROM table_1 a JOIN table_2 b ON some condition
UNION
SELECT NULL AS item_id , NULL AS quantity,... a.quantity AS number, b.quantity AS additional_number
FROM table_3 a JOIN table_4 b ON condition
)AS T
并且由于第一次选择中的SUM而仅以1行结束。
答案 0 :(得分:0)
试试这个:
SELECT item_ id,
(item.quantity - IFNULL(item_out.quantity,0)) AS quantity,
additional_id,
(IFNULL(a.quantity,0) - IFNULL(ao.quantity,0)) AS additional_quantity
FROM item
LEFT JOIN item_out
ON item.item_id = item_out.item_id
LEFT JOIN additional a
ON item.item_id = a.item_id
LEFT JOIN additional_out ao
ON a.addid = ao.additional_id