left join数据虚增
时间: 2023-11-03 21:22:10 浏览: 81
在使用left join时,如果在join条件中同时筛选了主表和从表的数据,会导致数据虚增的情况发生。举例来说,如果我们使用以下错误的SQL语句:
select c.*,s.* from class c left join student s on c.id = s.class_id where c.deleted = 0 and s.deleted =0
这样的写法会导致在class表和student表中都筛选了deleted=0的数据,这样会在结果集中产生虚增的数据,即class表中的某一条数据与student表中的多条数据进行了匹配,从而导致最终结果集中出现了重复的class数据。
正确的SQL语句应该是:
select c.*,s.* from class c left join student s on c.id = s.class_id and s.deleted =0 where c.deleted = 0
这样的写法将筛选条件放在join语句中,只对从表student进行筛选,而不对主表class进行筛选,避免了数据虚增的问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [MySQL left join 连表查询时右边的表添加过滤条件](https://blog.csdn.net/qq_30346433/article/details/105838154)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文