使用子查询和连接优化进行查询

时间:2016-02-10 03:41:42

标签: mysql join subquery

我某种方式对我的查询语句不满意,并且想知道是否还有其他更好的方法可以做到这一点:

SELECT product.product, 
 COALESCE((SELECT SUM(qty) FROM stocktrxn 
 INNER JOIN stock on stock.tra_no = stocktrxn.tra_no 
 WHERE product_no = s1.product_no and stock.is_out = false) - 
 (SELECT SUM(qty) FROM stocktrxn 
 INNER JOIN stock on stock.tra_no = stocktrxn.tra_no 
 WHERE product_no = s1.product_no and stock.is_out = true), 0)
 as qty
FROM stocktrxn s1
RIGHT JOIN product on product.id = s1.product_no
GROUP BY product ASC;

1 个答案:

答案 0 :(得分:1)

我认为你只想要条件聚合。像这样:

SELECT p.product,
       (SUM(CASE WHEN s.is_out = false THEN qty ELSE 0 END) -
        SUM(CASE WHEN s.is_out = true THEN qty ELSE 0 END) -
       ) as qty
FROM product LEFT JOIN
     stocktrxn st
     ON p.id = st.product_no LEFT JOIN
     stock s
     ON s.tra_no = st.tra_n
GROUP BY p.product ASC;