【发布时间】:2020-10-30 20:02:49
【问题描述】:
对于订单表中的每个订单,我都在尝试根据 time_sent 返回最新的订单更新值,并分组为一行。
CREATE TABLE order_updates (time_sent INTEGER, order_id INTEGER, a VARCHAR(2), b VARCHAR(2), c VARCHAR(2), d VARCHAR(2));
INSERT INTO order_updates (time_sent, order_id, a, b, c, d) VALUES
('1', '1', 'a1', null, null, null),
('2', '1', null, 'b1', null, null),
('3', '1', null, null, 'c0', null),
('4', '1', 'a3', null, 'c3', null),
('5', '1', 'a0', null, null, null),
('6', '2', 'a3', 'b0', null, 'd2'),
('7', '2', null, 'b3', null, null);
CREATE TABLE orders (order_id INTEGER, name VARCHAR(32));
insert into orders (order_id, name) values (1, "joe"), (2, "bill");
select *, (select order_updates.a from order_updates where order_updates.order_id = orders.order_id and order_updates.a is not null order by order_updates.time_sent desc limit 1) a,
(select order_updates.b from order_updates where order_updates.order_id = orders.order_id and order_updates.b is not null order by order_updates.time_sent desc limit 1) b,
(select order_updates.c from order_updates where order_updates.order_id = orders.order_id and order_updates.c is not null order by order_updates.time_sent desc limit 1) c,
(select order_updates.d from order_updates where order_updates.order_id = orders.order_id and order_updates.d is not null order by order_updates.time_sent desc limit 1) d
FROM orders;
上述选择查询在 MySql 中可以正常工作,但在 AWS Athena 中却不行。
下面的工作 MySQL 示例:
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=66f17cf9f3c8f19f758c7cb1381d8207
有没有办法使用连接来完成上述操作?
【问题讨论】:
-
只使用连接?如果不支持相关子查询,则根本无法使用它们。并非所有数据库都支持相同的功能。
-
有没有办法使用连接来完成上述操作?你能举个例子吗?
-
FWIW 您的查询在最新的 Presto (345) 中按原样工作。
-
做左连接,以防万一......
标签: sql amazon-athena