一張訂單表
estimate_id title
一張銷售表
sell_id estimate_id no sprice snum
一張採購表
buy_id estimate_id no bprice bnum
一個訂單對應多個銷售和採購(estimate_id),一個銷售對應多個採購(no)
查詢的結果:
title scount bcount
XX 10.00 5.00
BB (注:這種情況可能是隻有訂單,還沒有銷售和採購)
AA 100.00 45.00
.. .... .....
SQL語句:
SELECT e. * , s.scount, b.bcount
FROM tb_estimate AS e
LEFT JOIN (
SELECT SUM( sprice * snum ) AS scount, estimate_id
FROM tb_sell
WHERE deleted =0
GROUP BY estimate_id
) AS s ON e.estimate_id = s.estimate_id
LEFT JOIN (
SELECT SUM( bprice * bnum ) AS bcount, estimate_id
FROM tb_buy
WHERE deleted =0
GROUP BY estimate_id
) AS b ON b.estimate_id = e.estimate_id
WHERE e.deleted =0
ORDER BY updated DESC