php - 如何获取所有记录,即使是那些没有匹配连接的记录 - MySQL

标签 php mysql sql

我有以下 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/

相关文章:

php - 选择连接 MYSQL

php - 使用存储过程将值从 Controller 传递到模型 CodeIgniter

php - 在 html 标记之前必须调用哪些 session 函数

php - 与 FTP 服务器同步文件

mysql - 优化案例陈述的最佳方法是什么?

php - MySql 查询不能在 PHP 中工作,但可以在 phpMyAdmin 中工作

php - 从 MySQL 数据库查找下一个/上一个电视节目

mysql - 有人可以告诉我 slugging percentage 查询有什么问题吗?

php - 我如何从 xml 中获取第一个子元素?

SQL 在排序列中找到第一个大于 X 的值