SELECT\n\t\tplan.plan_id,\n\t\tplan.plan_name,\n\t\tplan.customer_type,\n\t\tplan.production_line_id,\n\t\tplan.manager,\n\t\tplan.description,\n\t\tplan.fenb_demand,\n\t\tplan.visit_times,\n\t\tplan.commucation_times,\n\t\tplan.training_times,\n\t\tplan.objective,\n\t\tplan.notifier,\n\t\tplan.YEAR,\n\t\tplan.create_by,\n\t\tplan.create_time,\n\t\tplan.update_by,\n\t\tplan.update_time,\n\t\tplan.tenant_id,\n\t\tplan.del_flag,\n\t\tplan.customer_id,\n\t\tinfo.customer_name,\n\t\tline.production_line_type,\n\t\tline.NAME production_line_name,\n\t\toa.plan_status\nFROM\n\t\tcm_maintenance_plan AS plan\nLEFT JOIN customer_management.cm_customer_info AS info ON plan.customer_id = info.customer_id\nLEFT JOIN customer_management.cm_production_line AS line ON plan.production_line_id = line.production_line_id\nLEFT JOIN pigxx_ac.oa_plan_examine as oa on plan.plan_id = oa.plan_id and oa.del_flag = 0\nWHERE\n\t\tplan.del_flag = 0\n\n在使用 LEFT JOIN 时,如果将过滤条件放在 WHERE 子句中,会导致关联表中满足条件的行被过滤掉,从而丢失部分数据。为了避免这种情况,应将过滤条件放在 LEFT JOIN 子句中,确保所有来自左表的行都能被保留。\n\n例如,在上面的 SQL 查询中,我们希望保留 cm_maintenance_plan 表中 del_flag 为 0 的所有数据,同时关联查询其他表。因此,我们将条件 "plan.del_flag = 0" 放置在 LEFT JOIN 子句中,而不是 WHERE 子句中。\n\n这样,我们就能确保在保留 cm_maintenance_plan 表中所有符合条件的数据的同时,也能获得关联表中的信息。

SQL 查询优化:LEFT JOIN 和 WHERE 子句的使用

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

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