从两个表中减去列

时间:2014-06-27 09:14:15

标签: mysql

我需要从两个表中获取总可用数量

Table T1
+-------------+------------+  
| Code        | Qty        |  
+-------------+------------+  
| A           | 500        |  
+-------------+------------+    


Table T2
+-------------+------------+  
| Code        | Qty        |  
+-------------+------------+  
| A           | 10         |  
+-------------+------------+    
| A           | 20         |  
+-------------+------------+    

使用此代码,我得到结果970而不是470:

SELECT
  `T1`.`Code`,
  (IFNULL(Sum(`T1`.`Qty`),0) - IFNULL(Sum(`T2`.`Qty`),0)) AS TotalQty
FROM
  `T1`
  LEFT JOIN `T2` ON `T1`.`Code` =
    `T2`.`Code`
GROUP BY
  `T1`.`Code`

我做错了什么?

3 个答案:

答案 0 :(得分:1)

检查此代码:)

SELECT Code,IFNULL(SUM(Qty),0)-IFNULL((SELECT SUM(Qty)FROM T2 WHERE T1.Code = Code),0)AS回答来自T1 GROUP BY代码

我编辑我的答案,因为你想在Code上添加一个条件,并且还要防止返回null值试试这个兄弟

答案 1 :(得分:0)

试试这个......

SELECT
  `T1`.`Code`,
  (IFNULL(`T1`.`Qty`,0) - IFNULL(Sum(`T2`.`Qty`),0)) AS TotalQty
FROM
  `T1`
  LEFT JOIN `T2` ON `T1`.`Code` =
    `T2`.`Code`
GROUP BY
  `T1`.`Code`

你会得到470。

答案 2 :(得分:0)

这应该有效

SELECT
  `T1`.`Code`, IFNULL(`T1`.`Qty`,0) - SUM(IFNULL(`T2`.`Qty`,0)
FROM
   T1
LEFT JOIN 
  T2 USING Code
GROUP BY Code