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

时间:2014-11-12 02:27:28

标签: mysql

我有一个查询为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的记录填充出货和结算列?

2 个答案:

答案 0 :(得分:2)

如果我理解正确的话,我会在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
                 )

答案 1 :(得分:1)

Haven没有对它进行过测试,但我认为:

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)