我有以下查询:
SELECT t1.id,
t1.collection_date,
t2.last_order_date,
t2.hasOrders
FROM job_details AS t1
LEFT JOIN
(
SELECT job_id,
MAX(date) AS last_order_date,
(CASE COALESCE(MAX(date), '0000-01-01') WHEN '0000-01-01' THEN 'false' ELSE 'true' END) AS hasOrders
FROM sales_orders
GROUP BY job_id
)
AS t2
ON t2.job_id = t1.id
我期望t2.hasOrders
的{{1}}部分之后的true
或false
或CASE
,但我一直得到LEFT JOIN
或将true
设为demonstrated here
我知道NULL
将始终返回有效日期或默认列值t2.date
。
这是我查询的简化版本,因为0000-00-00
正在查询的表是一个临时表。
为什么LEFT JOIN
的{{1}}值不返回我的预期结果?
谢谢。
编辑1
链接到演示-删除了查询的NULL
部分
编辑2
预期结果:
t2.date
实际结果:
where
编辑3
已将上述查询更新为在查询的id collection_date last_order_date hasOrders
1001 2019-02-07 2019-02-01 true
1002 2019-02-09 0000-01-01 false
部分中包含 id collection_date last_order_date hasOrders
1001 2019-02-07 2019-02-01 true
1002 2019-02-09 NULL NULL
,并根据建议将group by
更改为left join
。仍然无法正常工作。
答案 0 :(得分:1)
您需要将CASE WHEN移到外部查询,因为如果sales_orders
中没有行,则内部CASE WHEN将永远不会执行
SELECT t1.id,
t1.collection_date,
COALESCE(t2.last_order_date, '0001-01-01') order_date,
CASE COALESCE(t2.last_order_date, '0001-01-01')
WHEN '0001-01-01' THEN 'false'
ELSE 'true'
END flag
FROM job_details AS t1
LEFT JOIN
(SELECT job_id, MAX(date) AS last_order_date
FROM sales_orders
GROUP BY job_id
) AS t2
ON t2.job_id = t1.id
答案 1 :(得分:1)
我认为,通过将“ Max”和“ group by”移到外部语句,逻辑至少应该可以正常工作(如果您也要计算该列,则需要添加“ Coalesce”语句)。不确定性能如何,但是我首先会看看结果是否还可以。希望语法很好,还没有测试。
SELECT t1.id,
t1.collection_date,
MAX(t2.last_order_date)
FROM job_details AS t1
LEFT JOIN
(
SELECT job_id,
last_order_date
FROM sales_orders
)
AS t2
ON t2.job_id = t1.id
GROUP BY t1.id
答案 2 :(得分:0)
您必须输入t1.collection_date <= '2019-02-09'
,因为job_id 1002日期是'2019-02-09'
SELECT t1.id,
t1.collection_date,
t2.order_date,
t2.hasOrders
FROM job_details AS t1
LEFT JOIN
(
SELECT job_id,
MAX(date) AS order_date,
(CASE COALESCE(MAX(date), '0000-00-00') WHEN '0000-00-00' THEN 'false' ELSE 'true' END) AS hasOrders
FROM sales_orders group by job_id
)
AS t2
ON t2.job_id = t1.id
WHERE t1.collection_date <= '2019-02-09'