SQL 左连接查询优化:确保所有 cm_maintenance_plan 数据都包含

在使用 SQL 左连接查询时,如果要确保所有左表数据都包含,即使右表中没有匹配数据,需要注意 WHERE 条件的放置位置。

问题描述

以下 SQL 查询语句中,使用 LEFT JOIN 连接了多个表,并使用 WHERE 条件过滤了 del_flag 为 0 的数据。但实际查询结果中,cm_maintenance_plan 表中 del_flag 为 0 的某些数据却被过滤掉了。

SELECT
	plan.plan_id,
	plan.plan_name,
	plan.customer_type,
	plan.production_line_id,
	plan.manager,
	plan.description,
	plan.fenb_demand,
	plan.visit_times,
	plan.commucation_times,
	plan.training_times,
	plan.objective,
	plan.notifier,
	plan.YEAR,
	plan.create_by,
	plan.create_time,
	plan.update_by,
	plan.update_time,
	plan.tenant_id,
	plan.del_flag,
	plan.customer_id,
	info.customer_name,
	line.production_line_type,
	line.NAME production_line_name,
	oa.plan_status
FROM
	cm_maintenance_plan AS plan
LEFT JOIN customer_management.cm_customer_info AS info ON customer_management.plan.customer_id = info.customer_id
LEFT JOIN customer_management.cm_production_line AS line ON customer_management.plan.production_line_id = line.production_line_id
LEFT JOIN pigxx_ac.oa_plan_examine as oa on plan.plan_id = oa.plan_id
where
	plan.del_flag = 0
	and
	oa.del_flag = 0

原因分析

由于 WHERE 条件中的 plan.del_flag = 0,导致了原本应该包含在结果中的 cm_maintenance_plan 表数据被过滤掉。

解决方法

为了确保所有 cm_maintenance_plan 表中 del_flag 为 0 的数据都能查询到,可以将条件 plan.del_flag = 0 移动到左连接的 ON 子句中。

修改后的查询语句

SELECT
	plan.plan_id,
	plan.plan_name,
	plan.customer_type,
	plan.production_line_id,
	plan.manager,
	plan.description,
	plan.fenb_demand,
	plan.visit_times,
	plan.commucation_times,
	plan.training_times,
	plan.objective,
	plan.notifier,
	plan.YEAR,
	plan.create_by,
	plan.create_time,
	plan.update_by,
	plan.update_time,
	plan.tenant_id,
	plan.del_flag,
	plan.customer_id,
	info.customer_name,
	line.production_line_type,
	line.NAME production_line_name,
	oa.plan_status
FROM
	cm_maintenance_plan AS plan
LEFT JOIN customer_management.cm_customer_info AS info ON plan.customer_id = info.customer_id
LEFT JOIN customer_management.cm_production_line AS line ON plan.production_line_id = line.production_line_id
LEFT JOIN pigxx_ac.oa_plan_examine as oa on plan.plan_id = oa.plan_id and oa.del_flag = 0
WHERE
	plan.del_flag = 0

解释

  • LEFT JOIN 保证所有 cm_maintenance_plan 表数据都被包含。
  • 将 plan.del_flag = 0 放置在 ON 子句中,确保只有满足条件的 cm_maintenance_plan 数据才会进行匹配。
  • 同时保留 WHERE 子句中的 plan.del_flag = 0,以确保结果中只包含 del_flag 为 0 的数据。

总结

通过将 plan.del_flag = 0 条件移动到左连接的 ON 子句中,可以确保所有 cm_maintenance_plan 表中 del_flag 为 0 的数据都能查询到。

注意:

  • LEFT JOIN 的 ON 子句用来匹配两个表之间的关联关系,而 WHERE 子句用来过滤结果集。
  • 当需要确保左表所有数据都被包含时,不要将过滤条件放到 WHERE 子句中,而应该放在 ON 子句中。

希望以上内容对您有所帮助。如果您还有其他问题,请随时提问。

SQL 左连接查询优化:确保所有 cm_maintenance_plan 数据都包含

原文地址: https://www.cveoy.top/t/topic/qfSy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录