如何获得所有记录甚至那些没有匹配连接的记录 - MySQL

时间:2013-04-29 22:59:16

标签: php mysql sql

我有以下SQL获取所有客户记录,然后找到该客户的匹配文档(points_audit_customers.id = points_audit_documents._audit_id)并且它可以正常运行,但它正在跳过所有没有文档的客户匹配最初很好,但现在规格已经改变,我需要所有客户来,但如果没有找到文件,那么仍然显示客户详细信息,但保留sql中的文档字段为零或null。

这可能吗?我想知道是否可以使用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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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