繁体   English   中英

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

[英]MySQL how to populate query columns based on a condition?

我有一个查询,准备一些客户数据以进行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的记录填充装运和计费列?

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

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
                 )

还没有测试过,但我认为:

LEFT JOIN  CONTACT ct1 ON ct1.CON_CustomerID = cu.CU_CustomerID AND (ct1.CON_Type = 1 OR ct1.CON_Type = 3)

LEFT JOIN  CONTACT ct2 ON ct2.CON_CustomerID = cu.CU_CustomerID AND (ct2.CON_Type = 2 OR ct2.CON_Type = 3)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM