如何在MySQL的额外AS列中从AS值中减去AS值

时间:2013-06-24 09:21:53

标签: mysql sql

我的MySQL数据库中有两个表(tbl1tbl2)。现在,我写了一个像下面这样的查询来生成in_quantity和out_quantity的总和,其中serialno = AAA1 -

SELECT 
(
    SELECT 
        #GROUP_CONCAT(in_quantity), 
        SUM(in_quantity) GP FROM stockin WHERE serialno = 'AAA1'
) A,
(
    SELECT 
        #GROUP_CONCAT(out_quantity),
        SUM(out_quantity) SOP FROM stockout WHERE serialno = 'AAA1'
) B

此查询输出如下 -

+------+------+
| A    | B    |
+------+------+
|  800 |  740 |
+------+------+
1 row in set (0.00 sec)

现在,我需要以下结果 -

+------+------+------+
| A    | B    | C    |
+------+------+------+
|  800 |  740 |   60 |
+------+------+------+
1 row in set (0.00 sec)

我如何在查询中写这个?我在stackoverflow.com上查了几个帖子。但是,没有关于(AS A - AS B) = AS C

的地方

1 个答案:

答案 0 :(得分:0)

使用“A”“B”查询作为子查询:

SELECT q.A, q.B, q.A-q.B as C FROM
  (SELECT 
  (
    SELECT 
        #GROUP_CONCAT(in_quantity), 
        SUM(in_quantity) GP FROM stockin WHERE serialno = 'AAA1'
  ) A,
  (
    SELECT 
        #GROUP_CONCAT(out_quantity),
        SUM(out_quantity) SOP FROM stockout WHERE serialno = 'AAA1'
  ) B
  --following code
) q