MySQL变量是带有其他表元素的子查询的结果

时间:2019-04-19 03:58:45

标签: mysql

我有一个有效的查询:

SELECT count(*),
       AVG(
             (SELECT sum(order_fills.quant * order_fills.price)
              FROM order_fills
              WHERE `type`='closed'
                AND order_fills.transaction_id = transactions.id) -
             (SELECT sum(order_fills.quant * order_fills.price)
              FROM order_fills
              WHERE `type`='opened'
                AND order_fills.transaction_id = transactions.id)) AS avgProfit,
       SUM(
             (SELECT sum(order_fills.quant * order_fills.price)
              FROM order_fills
              WHERE `type`='closed'
                AND order_fills.transaction_id = transactions.id)) AS volume,
FROM transactions
WHERE transactions.status='closed';

为了使代码更具可读性,我希望将查询的某些部分设置为变量。

我希望实现类似的效果(此方法无效,返回null):

SET @transSells =
          (SELECT sum(order_fills.quant * order_fills.price)
           FROM order_fills
           WHERE type='closed'
             AND order_fills.transaction_id = transactions.id);


SET @transBuys =
          (SELECT sum(order_fills.quant * order_fills.price)
           FROM order_fills
           WHERE type='opened'
             AND order_fills.transaction_id = transactions.id);


SELECT avg(@transSells - @transBuys) AS `avgProfit`,
       sum(@transSells + @transBuys) AS `volume`
FROM transactions WHERE transactions.status='closed'

我认为问题可能在于子查询WHERE语句的一部分是主查询和另一个表(transactions.id)的结果:

AND order_fills.transaction_id = transactions.id

2 个答案:

答案 0 :(得分:1)

变量查询不起作用的原因是,变量定义的transactions.id子句中的WHERE未定义(NULL),因此查询不会返回任何内容结果。

我认为您可以使用条件聚合将变量放入派生表中,从而简化查询,然后JOIN执行以下操作:

SELECT AVG(transSells - transBuys) AS avgProfit,
       SUM(transSells + transBuys) AS volume
FROM transactions
JOIN (SELECT transaction_id,
             SUM(CASE WHEN type='closed' THEN quant * price ELSE 0 END) AS transSells,
             SUM(CASE WHEN type='opened' THEN quant * price ELSE 0 END) AS transBuys
      FROM order_fills) o ON o.transaction_id = transactions.id
WHERE status = 'closed'

答案 1 :(得分:0)

我为我的案件找到了一个更好的解决方案:

在查询中设置变量,然后在同一查询中使用它们。

 SET @comission = 0.03;

    SELECT count(*),
           AVG(
                 ( @transSells := (SELECT sum(order_fills.quant * order_fills.price)
                  FROM order_fills
                  WHERE `type`='closed'
                    AND order_fills.transaction_id = transactions.id)) 
                  -
                 ( @transBuys := (SELECT sum(order_fills.quant * order_fills.price)
                  FROM order_fills
                  WHERE `type`='opened'
                    AND order_fills.transaction_id = transactions.id))) AS avgProfit,

           SUM( @transSells ) AS volume,

           SUM( @transSells * @comission )

    FROM transactions
    WHERE transactions.status='closed';