gpt4 book ai didi

MySQL如何根据条件填充查询列?

转载 作者:太空宇宙 更新时间:2023-11-03 12:05:23 25 4
gpt4 key购买 nike

我有一个查询,正在为 CSV 导出准备一些客户数据:

SELECT cu.*, 
ct1.CON_FirstName AS billing_FirstName , ct1.CON_MiddleI AS billing_MiddleI , ct1.CON_LastName AS billing_LastName , ct1.CON_Address1 AS billing_CON_Address1 , ct1.CON_Address2 AS billing_CON_Address2 , ct1.CON_City AS billing_CON_City , ct1.CON_State AS billing_CON_State , ct1.CON_Province AS billing_Province , ct1.CON_Country AS billing_Country , ct1.CON_Zip AS billing_Zip , ct1.CON_Phone1 AS billing_Phone1 , ct1.CON_Phone2 AS billing_Phone2 , ct1.CON_Text AS billing_Text , ct1.CON_FriendlyName AS billing_FriendlyName , ct1.CON_Email AS billing_Email,
ct2.CON_FirstName AS shipping_FirstName , ct2.CON_MiddleI AS shipping_MiddleI , ct2.CON_LastName AS shipping_LastName , ct2.CON_Address1 AS shipping_CON_Address1 , ct2.CON_Address2 AS shipping_CON_Address2 , ct2.CON_City AS shipping_CON_City , ct2.CON_State AS shipping_CON_State , ct2.CON_Province AS shipping_Province , ct2.CON_Country AS shipping_Country , ct2.CON_Zip AS shipping_Zip , ct2.CON_Phone1 AS shipping_Phone1 , ct2.CON_Phone2 AS shipping_Phone2 , ct2.CON_Text AS shipping_Text , ct2.CON_FriendlyName AS shipping_FriendlyName , ct2.CON_Email AS shipping_Email

FROM CUSTOMERS cu

LEFT JOIN CONTACT ct1 ON ct1.CON_CustomerID = cu.CU_CustomerID AND ct1.CON_Type = 1

LEFT JOIN CONTACT ct2 ON ct2.CON_CustomerID = cu.CU_CustomerID AND ct2.CON_Type = 2

GROUP BY cu.CU_CustomerID

ORDER BY cu.CU_CustCatId DESC

我的问题是第三个 CON_Type 值为“3”,这意味着联系信息既是账单信息又是运送信息。即一些用户在 CONTACT 表中有两个条目,而其他 [其运费和账单相同] 只有一个条目。

如何为只有 CON_Type = 3 的记录填充运输和账单列?

最佳答案

如果我理解正确的话,我会在 on 子句中使用 in:

from 子句看起来像:

FROM CUSTOMERS cu LEFT JOIN 
CONTACT ct1
ON ct1.CON_CustomerID = cu.CU_CustomerID AND ct1.CON_Type IN (1, 3) LEFT JOIN
CONTACT ct2
ON ct2.CON_CustomerID = cu.CU_CustomerID AND ct2.CON_Type IN (2, 3)

如果你想排除类型 1 和 2(以及其他类型),那么你可以将它们过滤掉:

FROM CUSTOMERS cu LEFT JOIN 
CONTACT ct1
ON ct1.CON_CustomerID = cu.CU_CustomerID AND ct1.CON_Type = 3 LEFT JOIN
CONTACT ct2
ON ct2.CON_CustomerID = cu.CU_CustomerID AND ct2.CON_Type = 3
WHERE NOT EXISTS (SELECT 1
FROM CUSTOMERS cu2
WHERE cu2.CU_CustomerID = cu.CU_CustomerID and
cu2.CON_Type <> 3
)

关于MySQL如何根据条件填充查询列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26878226/

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