一、什么是连接查询:就是将二个或二个以上的表,“连接起来”当做一个数据源,并从中去取得所须要的数据。连接查询包括交叉连接查询、内连接查询、外连接查询
(一)交叉连接:交叉连接不带WHERE子句,它返回被连接的两个表所有数据行的笛卡尔积,返回结果集合中的数据行数等于第一个表中符合查询条件的数据行数乘以第二个表中符合查询条件的数据行数。
1、格式1:select 要查询的内容 from 表名1 cross join 表名2;
2、格式2:select 要查询的内容 from 表名1,表名2…;
3、格式3:select 要查询的内容 from 表名1 join 表名2;
select * from department,employee;
(二)内连接:内连接也叫连接,是最早的一种连接。还可以被称为普通连接或者自然连接,内连接是从结果表中删除与其他被连接表中没有匹配行的所有行,所以内连接可能会丢失信息。
1、方法1:select 要查询的内容 from 表名1,表名2… where 表1.字段名=表2.字段名;
2、方法2:select 要查询的内容 from 表名1 join 表名2 where 表1.字段名=表2.字段名;
3、方法3:select 要查询的内容 from 表名1 cross join 表名2 where 表1.字段名=表2.字段名;
4、方法4:select 要查询的内容 from 表名1 inner join 表名2 on 表1.字段名=表2.字段名;
5、方法5:select 要查询的内容 from 表名1 join 表名2 on 表1.字段名=表2.字段名;
6、注意:在使用内连接时,可以给表起别名,格式为select 要查询的内容 from 表名1 别名1 join 表名2 别名2 on 别名1.字段名=别名2.字段名;
select * from department inner join employee on department.did = employee.did;
select * from department as d inner join employee as e on d.did = e.did;
select * from department d inner join employee e on d.did = e.did;
select * from department d inner join employee e on d.did > e.did;
select department.*,employee.id,name,age from department inner join employee on department.did = employee.did;
自然连接
select * from department natural join employee;
select * from orders cross join customers;
select * from orders inner join customers on customers.customer_id = orders.customer_id ;
(三)外链接:只限制一张表中的数据必须满足连接条件,而另一张表中的数据可以不满足连接条件的连接方式,外连接分为左外连接、右外连接、全外连接</