情况
在数据分析的时候 需要 costtable,shoptable两个表做左连接,costtable为主表,从shoptable两个表做左连接表中通过orderid拿shopname字段。
select id,orderIdA,product from costtable
left join
select orderIdB,shopName from shoptable
完整sql如下:
select id,orderIdA,product,orderIdB,shopName from costtable LEFT JOIN shoptable on costtable.orderIdA = shoptable.orderIdB
或者
SELECT id,orderIdA,product,orderIdB,shopName from costtable ,shoptable where costtable.orderIdA = shoptable.orderIdB
查看结果发现里面有多条一模一样的数据。
原因
shoptable中有多条orderIdB重复的数据,orderIdB重复n条总的结果里就会重复n条
原因是 虽然 我们使用的是left join,但是 orderIdB有多条时,底层的算法 无法识别 到底取哪一条,就会n条数据都做连接返回。
解决方案
在查询orderIdB时 确保没有重复的数据,使用DISTINCT
sql语句修改如下:
select id,orderIdA,product from costtable