1

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

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

2 回答 2

3

您需要使用外部联接

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
于 2013-04-29T23:00:40.443 回答
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
于 2013-04-29T23:08:25.867 回答