createtable t1 (id intprimarykey,name varchar(10));insertinto t1 values(1,'a');insertinto t1 values(2,'b');createtable t2 (id intprimarykey,name varchar(10));insertinto t2 values(1,'a');insertinto t2 values(2,'b');createtable t3 (id int,name varchar(10));insertinto t3 values(1,'a');insertinto t3 values(1,'a');insertinto t3 values(2,'b');insertinto t3 values(2,'b');insertinto t3 values(null,'n');
MySQL [test]>select*from t1;+----+------+| id | name |+----+------+|1| a ||2| b |+----+------+2rowsinset(0.01 sec)
MySQL [test]>select*from t2;+----+------+| id | name |+----+------+|1| a ||2| b |+----+------+2rowsinset(0.00 sec)
MySQL [test]>select*from t3;+------+------+| id | name |+------+------+|1| a ||1| a ||2| b ||2| b ||NULL| n |+------+------+4rowsinset(0.00 sec)
in 改写 join 情况1 ,一比一的关系
在这里插入情况1 ,一比一的关系
select*from t1 where t1.id in(select id from t2);+----+------+| id | name |+----+------+|1| a ||2| b |+----+------+select*from t1,t2 where t1.id = t2.id;+----+------+| id | name |+----+------+|1| a ||2| b |+----+------+代码片
in 改写 join 情况1 ,一对多的关系
select*from t1 where t1.id in(select id from t3);+----+------+| id | name |+----+------+|2| b ||1| a |+----+------+
正确改写 innerjoinselect t1.*from t1 innerjoin(selectdistinct(id)from t3) tt where t1.id = tt.id;+----+------+| id | name |+----+------+|2| b ||1| a |+----+------+
正确改写 leftjoinselect t1.*from t1 leftjoin(selectdistinct(id)from t3) tt on t1.id = tt.id;+----+------+| id | name |+----+------+|1| a ||2| b |+----+------+
错误改写
select t1.*from(selectdistinct(id)from t3) tt leftjoin t1 on t1.id = tt.id and tt.id isnotnull;+------+------+| id | name |+------+------+|NULL|NULL||2| b ||1| a |+------+------+
错误改写
select t1.*from t1 leftjoin t3 on t1.id=t3.id;+----+------+| id | name |+----+------+|1| a ||1| a ||2| b ||2| b |+----+------+
错误改写
select*from t1,t3 where t1.id = t3.id;+----+------+| id | name |+----+------+|1| a ||1| a ||2| b ||2| b |+----+------+