簡體   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