我有以下 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
最佳答案
您需要使用 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
关于php - 如何获取所有记录,即使是那些没有匹配连接的记录 - MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16289620/