优化我的Mysql查询以获取库存状态

时间:2015-12-17 06:52:37

标签: php mysql

这是我的mysql查询:

SELECT 
    (SELECT SUM(jb_qty) FROM tbl_transactions WHERE jb_Type=1 AND jb_s_Id=$s_Id) AS purqty, 
    (SELECT SUM(jb_qty) FROM tbl_transactions WHERE jb_Type=2 AND jb_s_Id=$s_Id) AS salqty
FROM tbl_transactions LIMIT 1

获取库存状态(jb_type 1为购买,2为销售。

我也希望获得当前的库存状态(例如purqty-salqty),并且需要更好的查询才能获得这些结果。

1 个答案:

答案 0 :(得分:3)

这里有一些你可以很容易改进的东西。首先,您可以消除子查询,只使用带有case表达式的单个查询,因此相同的行只会被处理一次。其次,由于两个查询的jb_s_Id条件相同,您可以再次将其移出where子句,以减少查询需要处理的行数:

SELECT SUM(CASE jb_type WHEN 1 THEN jb_qty END) AS purqty,
       SUM(CASE jb_type WHEN 2 THEN jb_qty END) AS salqty
FROM   tbl_transactions
WHERE  jb_s_Id = $s_Id

修改
要回答评论中的问题,如果你想从purqty中减去salqty,你可以在两个表达式之间使用-运算符:

SELECT SUM(CASE jb_type WHEN 1 THEN jb_qty END) AS purqty,
       SUM(CASE jb_type WHEN 2 THEN jb_qty END) AS salqty
       SUM(CASE jb_type WHEN 1 THEN jb_qty END) - 
       SUM(CASE jb_type WHEN 2 THEN jb_qty END) AS diff
FROM   tbl_transactions
WHERE  jb_s_Id = $s_Id

更优雅的方法是使用子查询,因此您不必重复相同的表达式两次:

SELECT purqty, salqty, purqty - salqty
FROM   (SELECT SUM(CASE jb_type WHEN 1 THEN jb_qty END) AS purqty,
               SUM(CASE jb_type WHEN 2 THEN jb_qty END) AS salqty
        FROM   tbl_transactions
        WHERE  jb_s_Id = $s_Id) t