gpt4 book ai didi

mysql - 连接 4 个表导致空结果

转载 作者:可可西里 更新时间:2023-11-01 07:38:16 25 4
gpt4 key购买 nike

我有 4 个表,每个表上都有这个细节

deli_order 表

order_code | code | plat_create_time | status
OC001 C001 2019-04-14 Success
OC002 C002 2019-04-14 Success
OC003 C003 2019-04-14 Success

pg_order 表

id |order_code | code | plat_create_time
1 OC001 C001 2019-04-14
2 OC002 C002 2019-04-14
3 OC003 C003 2019-04-14

pg_package 表

pg_order_id | plat_create_time | cm_sign_time
1 2019-04-14 2019-04-14
2 2019-04-14 2019-04-14
3 2019-04-14 -

pg_send_package 表

order_code | code | plat_create_time | lp_sign_time
OC001 C001 2019-04-14 -
OC002 C002 2019-04-14 -
OC003 C003 2019-04-14 2019-04-14

我需要计算具有“cm_sign_time”或“lp_sign_time”的交易数据。 pg_package 表需要先连接到 pg_order,然后才能连接到 deli_order 表。

首先,我首先尝试将 pg_send_package 表与 deli_order 表连接起来。这是我的查询

SELECT 
DATE(A.create_time) AS 'Create Time',
SUM(CASE
WHEN B.lp_sign_time IS NOT NULL THEN 1
ELSE 0
END) AS 'Completed Order'
FROM
deli_order A
INNER JOIN pg_send_package B ON B.order_code = A.order_code AND B.code = A.code
WHERE DATE(A.plat_create_time) = '2019-04-14'
GROUP BY DATE(A.plat_create_time);

结果

Create Time | Completed Order
2019-04-14 130

但是当我加入另外两个表时,我得到的结果是什么都没有。这是我的查询

SELECT 
DATE(A.plat_create_time) AS 'Create Time',
SUM(CASE
WHEN B.lp_sign_time IS NOT NULL THEN 1
WHEN D.cm_sign_time IS NOT NULL THEN 1
ELSE 0
END) AS 'Completed Order'
FROM
deli_order A
INNER JOIN pg_send_package B ON B.order_code = A.order_code AND B.code = A.code
INNER JOIN pg_order C ON C.order_code = A.order_code AND C.oms_code = A.code
INNER JOIN pg_package D ON D.pg_order_id = C.id
WHERE
DATE(A.plat_create_time) = '2019-04-14'
GROUP BY DATE(A.plat_create_time);

这是结果

Create Time | Completed Order

我需要对带有“lp_sign_time”或“cm_sign_time”的交易的计数结果求和。

我的预期结果是

Create Time | Completed Order
2019-04-14 150

150 来自带有“lp_sign_time”的 130 笔交易和带有“cm_sign_time”的 20 笔交易我应该在查询中更改什么?

最佳答案

你可以尝试使用UNION ALL结合pg_send_packagepg_package表为order_code,code,lp_sign_time 然后使用 COUNT 执行 OUTER JOIN

SELECT DATE(A.plat_create_time) AS 'Create Time', 
COUNT(lp_sign_time) AS 'Completed Order'
FROM deli_order A
LEFT JOIN
(
SELECT order_code,
code,
lp_sign_time
FROM pg_send_package psp
UNION ALL
SELECT C.order_code,
C.code,
pp.cm_sign_time
FROM pg_package pp
INNER JOIN pg_order C ON pp.pg_order_id = C.id
) t1 ON t1.order_code = A.order_code
AND t1.code = A.code
AND DATE(A.plat_create_time) = '2019-04-14'
GROUP BY DATE(A.plat_create_time);

关于mysql - 连接 4 个表导致空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55827623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com