How to use subquery table alias in WHERE clause in MySQL

白昼怎懂夜的黑 提交于 2020-01-30 08:08:48

问题


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); 

When I tried to use the TEMP_TABLE, an error occurred and said TEMP_TABLE doesn't exist. Why doesn't it work? I think the execution order is "FROM" then "WHERE", the table alias has been created at that time.


回答1:


You can't calculate max for the previously calculated alias in sub query alternatively you can rewrite your query as

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

I have created a sample demo for testing purpose

Sample data

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

In above query you can see maximum sum of amount for invoice is 10 so invoice_id =>1,2 should be returned 1 has amount of 10 and two entries for invoice_id => 2 (5+5 = 10) is also 10 ,3 and 4 should not be included in result set sample output

invoice_id  sum_amount  max_amount
1           10          10
2           10          10

DEMO



来源:https://stackoverflow.com/questions/30018373/how-to-use-subquery-table-alias-in-where-clause-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!