sql select 具有多个命名表的子查询中的 max()
sql select max() in subquery with multiple named tables
此查询有效:
SELECT * FROM essenbestellung WHERE Zaehler = (SELECT MAX(Zaehler) FROM essenbestellung WHERE Kind='0' AND Datum='02.08.2021');
给出结果:
Kind Datum Zaehler
0 02.08.2021 1
但是我想合并多个表,所以我必须给它们命名,例如e1
。我想知道为什么这个查询不起作用:
SELECT * FROM essenbestellung e1 WHERE e1.Zaehler=(SELECT MAX(e1.Zaehler) FROM essenbestellung WHERE e1.Kind='0' AND e1.Datum='02.08.2021');
给出两个结果:
Kind Datum Zaehler
0 02.08.2021 0
0 02.08.2021 1
如果我将查询更改为
e1.Zaehler=(SELECT MAX(e1.Zaehler) FROM e1...
我收到错误
table 'database.e1' doesn't exist
我怎样才能让它工作?谢谢
因为您的子查询引用了 outer 查询中的别名。给所有 tables 别名并适当地使用它们:
SELECT e1.*
FROM essenbestellung e1
WHERE e1.Zaehler = (SELECT MAX(e2.Zaehler)
FROM essenbestellung e2
WHERE e2.Kind = '0' AND e2.Datum = '02.08.2021'
);
注意子查询中的过滤在这个版本中只针对子查询中的table
此查询有效:
SELECT * FROM essenbestellung WHERE Zaehler = (SELECT MAX(Zaehler) FROM essenbestellung WHERE Kind='0' AND Datum='02.08.2021');
给出结果:
Kind Datum Zaehler
0 02.08.2021 1
但是我想合并多个表,所以我必须给它们命名,例如e1
。我想知道为什么这个查询不起作用:
SELECT * FROM essenbestellung e1 WHERE e1.Zaehler=(SELECT MAX(e1.Zaehler) FROM essenbestellung WHERE e1.Kind='0' AND e1.Datum='02.08.2021');
给出两个结果:
Kind Datum Zaehler
0 02.08.2021 0
0 02.08.2021 1
如果我将查询更改为
e1.Zaehler=(SELECT MAX(e1.Zaehler) FROM e1...
我收到错误
table 'database.e1' doesn't exist
我怎样才能让它工作?谢谢
因为您的子查询引用了 outer 查询中的别名。给所有 tables 别名并适当地使用它们:
SELECT e1.*
FROM essenbestellung e1
WHERE e1.Zaehler = (SELECT MAX(e2.Zaehler)
FROM essenbestellung e2
WHERE e2.Kind = '0' AND e2.Datum = '02.08.2021'
);
注意子查询中的过滤在这个版本中只针对子查询中的table