sql语句-关于自身表连接之join与left join

来源:互联网 发布:五十知天命什么意思 编辑:程序博客网 时间:2024/05/22 06:25

1、创建表

drop table if exists t_user;create table t_user(id int(11) not null auto_increment,user_id int(11),user_name varchar(100),primary key(id))engine=Innodb default charset=utf8;

2、插入测试数据

insert into t_user values(1,1,'admin');insert into t_user values(2,2,'superadmin');

3、表自身关联-join

select * from t_user t1  join (select * from t_user) t2 on t1.id=1 and t2.id=2

 

4、表自身关联-left join

select * from t_user t1  left join (select * from t_user) t2 on t1.id=1 and t2.id=2

总结:

1)表的自关联是通过把一个表命名不同的名称,然后找到想要关联的关系进行关联;

2)左连接left join查询出来的结果不仅仅是on 后面条件关联的数据,还包括条件中没有关联到的但是左边的select查询到的结果,没有关联到的数据部分用NULL填充。

0 0