sql - 基于日期评估的子查询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 天时,才应返回最终结果。
提前为糟糕的解释道歉,但希望很清楚我在这里想要达到的目标。此外,我没有提出这个数据库架构并且鉴于项目限制,我无法更改架构。
谢谢!
解决方案
使用横向连接:
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
推荐阅读
- python - 获取输入元素硒python的文本
- angular - Angular/tailwindcss 在不需要时阻止 sass/css 编译
- machine-learning - Julia vs Rust ML 哪个是最好的路径?
- flutter - 参数类型'CurrentUser? 函数(用户)”不能分配给参数类型“当前用户函数(用户?)”
- linux - 为什么在使用 yarn global 命令安装 angular-cli 后 ng --version 命令不起作用?
- google-chrome - 为什么谷歌浏览器会发出比文件大小更大范围的http下载请求以及如何处理?
- python - 硒更多结果xpath
- python - Python 模拟的 ASCII85 编码的“Adobe 实现”是什么?
- javascript - 在没有线性搜索的情况下检查数组中是否存在元素
- php - 使用 Gravity Forms Product Add-ons + Woocommerce,可以创建添加到购物车的链接吗?