首页 > 解决方案 > 基于日期评估的子查询JOIN

问题描述

我有一个查询,其中包含一个子查询,该子查询引用了我的查询加入的一个表,但我还需要对从 WHERE 子句中的子查询返回的字段进行评估。

这是当前查询(粗略示例) -

SELECT t1.first_name, t1.last_name, 
(SELECT created_at FROM customer_order_status_history WHERE order_id=t2.order_id AND order_status=t2.order_status ORDER BY created_at DESC LIMIT 1) AS order_date
FROM customers AS t1
INNER JOIN customer_orders as t2 on t2.customer_id=t1.customer_id

我的子查询目前正在从 customer_order_status_history 表中返回最新日期,但在我的查询中,我想对 WHERE 子句中的子查询进行评估,这样我只需要最近的 created_at 日期大于特定日期条件(即系统日期 - 5 天)。因此,在某种程度上,这是对 customer_orders 和 customer_order_status_history 表的条件连接,只有当 customer_order_status_history 中的最新记录(按 created_at 降序排序)大于系统日期 - 5 天时,才应返回最终结果。

提前为糟糕的解释道歉,但希望很清楚我在这里想要达到的目标。此外,我没有提出这个数据库架构并且鉴于项目限制,我无法更改架构。

谢谢!

标签: sqlpostgresql

解决方案


使用横向连接:

SELECT c.first_name, c.last_name, cosh.created_at
FROM customers c INNER JOIN
     customer_orders co
     ON co.customer_id = c.customer_id CROSS JOIN LATERAL
     (SELECT cosh.*
      FROM customer_order_status_history cosh
      WHERE cosh.order_id = co.order_id AND
            cosh.order_status = co.order_status AND
            cosh.created_at > now() - INTERVAL '5 DAY'
      ORDER BY cosh.created_at DESC
      LIMIT 1
     ) cosh

推荐阅读