使用派生子查询会导致其他查询

时间:2017-08-03 10:18:16

标签: mysql sql subquery

我想在下一个select中使用第一个子查询结果。但它没有看到row1,因为它不是数据库中的表。我该如何解决这个问题?

UPDATE transactions, (SELECT
                    card_id,
                    id,
                    card_sum_before,
                    card_sum_after,
                    amount,
                    dt
                  FROM transactions
                  WHERE status = 1 AND
                        card_id = 1
                  ORDER BY dt ASC) AS counted_table,
  (SELECT
 row2.id                                                   AS id,
 (row1.card_sum_after - row2.amount - row2.card_sum_after) AS difference
FROM counted_table AS row1
 INNER JOIN counted_table AS row2 ON row2.id = row1.id + 1
ORDER BY row1.dt ASC) selected
SET transactions.difference = selected.difference
WHERE transactions.id = selected.id`

1 个答案:

答案 0 :(得分:0)

请执行类似操作,将第一个查询输出存储到临时表,然后在您想要的任何查询中使用该临时表。