数据库-连接查询 总汇

版权声明: https://blog.csdn.net/wangzhonglinqwe/article/details/83153487

内连接、外连接、自然连接

内连接:

select someColumn from table1 inner join table2 on condition(=、>、<、in 、not in、between and)
效果: 查询 符合 condition的2张表的数据
在这里插入图片描述

外连接

  • 左外连接
    select someColumn from table1 left join table2 on condition(=、>、<、in 、not in、between and)
    效果:查询符合约束的以左表为基准的数据(右边如无对应则显示null)
  • 右外连接
    select someColumn from table1 rightjoin table2 on condition(=、>、<、in 、not in、between and)
    效果:查询符合约束的以右表为基准的数据(左边如无对应则显示null)
    建表语句:
create table lt1(
id int primary key auto_increment,
age int not null
);
aler table lt1 rename lt;
alter table lt modify id int auto_increment;  
insert into rt(age) values(1);

在这里插入图片描述
在后面添加where约束,则是对该结果集的进一步筛选;1和3列的列名相同但是分属于不同表;where left.id=1结果如下:
在这里插入图片描述
where rigth.id=1 结果如下:
在这里插入图片描述

  • 自然连接
    不同于内连接,没有显式的约束条件,而是相同的列名自然进行等值连接
select * from lt natural join rt;

在这里插入图片描述
由于进行的是列名的完全等值匹配,所以结果集中的列名在用where约束时候,rt.idlt.id 效果一样

猜你喜欢

转载自blog.csdn.net/wangzhonglinqwe/article/details/83153487