首页 > 解决方案 > 使用使用组函数的外部列连接子查询

问题描述

所以这个对你们大多数人来说应该很简单:

我的表有一个 ID、一个 order_id 和一个状态。同一个 order_id 可能有多个 ID。

我需要做的是从每个 order_id 中获取最后一个 ID,这非常简单:

SELECT order_id, max(ID) AS last_id 
FROM mytable
GROUP BY order_id

现在,我还需要获取与最后一个 ID 相关联的状态,所以我想做的是:

SELECT order_id, max(ID) AS last_id, x.status
FROM mytable t

LEFT JOIN (SELECT ID, status
          FROM mytable) x ON last_id = x.ID

我知道我不允许使用 last_id 别名来加入子查询,因为它说它不存在。那么我该怎么做呢?

标签: sqlpostgresqljoinsubquery

解决方案


您不能在查询FROM的部分或WHERE部分中使用别名,您应该使用max(t.ID)

SELECT order_id, max(t.ID) AS last_id, x.status
FROM mytable t

LEFT JOIN (SELECT ID, status
          FROM mytable) x ON MAX(t.ID) = x.ID

您还可以将查询包装为子查询,然后使用别名进行连接:

SELECT t.order_id, t.last_id, x.status
FROM (
  SELECT order_id, max(ID) AS last_id
  FROM mytable
) t
LEFT JOIN mytable x
ON t.last_id = x.ID

推荐阅读