2013-04-29 70 views
1

我有以下SQL獲取所有客戶記錄,然後找到該客戶的匹配文檔(points_audit_customers.id = points_audit_documents._audit_id),但它的工作原理它跳過所有沒有文件匹配的客戶,原本很好,但現在規範已經改變,我需要所有的客戶來,如果沒有找到文件,仍然顯示客戶的詳細信息,但離開文件字段sql爲零或null。如何獲取所有記錄,即使那些沒有匹配的連接 - MySQL

這可能嗎?我想知道是否可以使用CASE嗎?我想如果這是不可能的,我可以修改SQL來只選擇客戶的詳細信息,然後在PHP循環中選擇匹配的文檔,理想情況下,如果可以的話,我寧願用SQL語句來完成。

三江源

SELECT points_audit_customers.*, points_audit_documents.branch, 
SUM(points_audit_documents.amount_invoiced) AS the_amount_invoiced, 
SUM(points_audit_documents.amount_spent) AS the_amount_spent,  
SUM(points_audit_documents.points_invoiced) as invoiced_points, 
SUM(points_audit_documents.points_spent) as spent_points, 
SUM(points_audit_documents.points_bonus) as bonus_points 
FROM points_audit_customers, points_audit_documents 
WHERE import_month = '$import_month' 
AND points_audit_customers.id = points_audit_documents.audit_id 
AND processed = 1 

回答

3

您需要使用outer join

FROM points_audit_customers LEFT JOIN points_audit_documents 
     ON points_audit_customers.id = points_audit_documents.audit_id 
WHERE import_month = '$import_month' 
    AND processed = 1 -- if this is in documents table, move to the join criteria 
+0

感謝。這工作。 – sluggerdog 2013-04-30 01:05:33

0
SELECT pac.*, pad.branch, 
    IFNULL(SUM(pad.amount_invoiced), 0) AS the_amount_invoiced, 
    IFNULL(SUM(pad.amount_spent), 0) AS the_amount_spent,  
    IFNULL(SUM(pad.points_invoiced), 0) AS invoiced_points, 
    IFNULL(SUM(pad.points_spent), 0) AS spent_points, 
    IFNULL(SUM(pad.points_bonus), 0) AS bonus_points 
FROM points_audit_customers pac 
LEFT JOIN points_audit_documents pad ON (pad.id = pac.audit_id) 
WHERE processed = 1 
    AND import_month = '$import_month' 
GROUP BY pac.id 
相關問題