0
有3個表優化查詢
Table min consist of matcode,min_qty,jo_no,mr_no,min_no
Table min_out_body consist of matcode,out_qty,jo_no,mr_no,min_no
Table eu_min_out_body consist of matcode,out_qty,jo_no,mr_no,min_no
和數據如下的結構:
[min]
matcode min_qty jo_no mr_no min_no
xxx 100 1A A11 A111
xxx 150 2A A22 A222
yyy 100 1A A11 A111
zzz 150 2A A22 A222
[min_out_body]
matcode out_qty jo_no mr_no min_no
xxx 10 1A A11 A111
xxx 60 1A A11 A111
xxx 100 2A A22 A222
yyy 100 1A A11 A111
[eu_min_out_body]
matcode out_qty jo_no mr_no min_no
xxx 20 1A A11 A111
xxx 50 2A A22 A222
zzz 100 2A A22 A222
什麼,我想實現的是有一個結果:
matcode min_qty jo_no mr_no balance
xxx 100 1A A11 10
zzz 150 2A A22 50
使用以下代碼查詢:
SELECT
min.matcode,
min.min_qty,
min.jo_no,
min.mr_no,
(min.min_qty-(
select ifnull(sum(out_qty),0)
FROM min_out_body
WHERE min_no=min.min_no
and matcode=min.matcode
and jo_no=min.jo_no
and mr_no=min.mr_no
)-(
select ifnull(sum(out_qty),0)
FROM eu_min_out_body
WHERE min_no=min.min_no
and matcode=min.matcode
and jo_no=min.jo_no
and mr_no=min.mr_no
)
) as balance
FROM min
WHERE (min.min_qty - (select
ifnull(sum(out_qty),0)
FROM min_out_body
WHERE min_no=min.min_no
and matcode = min.matcode
and jo_no = min.jo_no
and mr_no = min.mr_no) - (select
ifnull(sum(out_qty),0)
FROM eu_min_out_body
WHERE min_no=min.min_no
and matcode = min.matcode
and jo_no = min.jo_no
and mr_no = min.mr_no)) > 0
我可以得到結果,但是有什麼辦法可以簡化查詢並減少處理時間嗎?
下面是從SQL小提琴樣本數據sqlfiddle.com/#!2/1fb8b/1
你能解釋一下如何處理這3個原始表格以產生這兩行? –