如何在MySQL

时间:2015-05-03 19:26:39

标签: mysql subquery

SELECT invoice_id, sum_amount
FROM (SELECT invoice_id, SUM(amount) AS sum_amount
      FROM invoice
      GROUP BY invoice_id) AS TEMP_TABLE
WHERE sum_amount in (SELECT MAX(sum_amount) 
                     FROM TEMP_TABLE); 

当我尝试使用TEMP_TABLE时,发生错误并且TEMP_TABLE表示不存在。为什么不起作用?我认为执行顺序是“FROM”然后是“WHERE”,表格别名是在那时创建的。

1 个答案:

答案 0 :(得分:2)

您无法在子查询中计算先前计算的别名的最大值,或者您可以将查询重写为

SELECT a.invoice_id, SUM(a.amount) AS sum_amount,
c.max_amount
FROM invoice AS a
CROSS JOIN (
      SELECT MAX(sum_amount) max_amount FROM(
          SELECT invoice_id, SUM(amount) AS sum_amount
          FROM invoice
          GROUP BY invoice_id
      ) b
) c
GROUP BY a.invoice_id
HAVING sum_amount = c.max_amount

我已经为测试目的创建了一个示例演示

示例数据

INSERT INTO invoice
    (`invoice_id`, `amount`)
VALUES
    (1, 10),
    (2, 5),
    (2, 5),
    (3, 1),
    (4, 2);

在上面的查询中,您可以看到发票金额的最大金额为10,因此应返回JAN_id => 1,2返回1金额为10,发票金额为2的条目=> 2(5 + 5 = 10)也是10,3和4不应包括在结果集样本输出

invoice_id  sum_amount  max_amount
1           10          10
2           10          10

DEMO