Mysql之多表查询
1.复制表
作用: 备份表 和 快速建表
命令格式: create table 库.表 sql查询命令; //复制的内容由sql查询命令决定,不会复制源表字段的键值给新表
2.复制表结构及数据到新表
create table 新表 select * from 旧表 //不会复制主键类型和自增方式
3.只复制表结构到新表
create table 新表 select * from 旧表 where 1=2; //不会复制主键类型和自增方式
create table 新表 like 旧表 ; //把旧表的所有字段类型都复制到新表
4.复制旧表的数据到新表(假设两个表结构一样)
insert into 新表 select * from 旧表
5.复制旧表的数据到新表(假设两个表结构不一样)
insert into 新表(字段1,字段2,…….) select 字段1,字段2,……from 旧表
6.where嵌套查询
定义: 把内层的查询结果作为外层查询的查询条件
命令格式: select 字段名列表 from 库.表 where 条件 ( select 字段名列表 from 库.表 where 条件 );
select name,uid from xx where uid > (select avg(uid) from xx); //同表
select name from user where name in (select user from mysql.user where host="localhost"); //不同表
7.多表查询(又称 连接查询——交叉连接 自然连接 内连接 外连接(左连接、右连接))
将2个或 2 个以上的表按某个条件连接起来,选取需要的数据,当多个表中存在相同意义的字段(字段名可以不同)时,可以通过该字段连接多个表
命令格式: select 字段名列表 from 表名列表 [ where 匹配条件];
格式 1 select 字段名列表 from 表 a, 表 b ;
格式 2 select 字段名列表 from 表 a, 表 b where 条件;
查询结果叫笛卡尔集(笛卡尔集通常出现在表查询当中,是多种查询结果中集合的一种) 显示查询结果的总条目数是 (表 a 的纪录数 * 表 b 的纪录数)
select * from t1,t2; //笛卡尔集
select * from t1,t2 where t1.uid=t2.uid;
select t1.shell,t2.* from t1,t2 where t1.uid=t2.uid;
8.外连接
(1)左连接查询 (当匹配条件成立时 以左表为主显示查询记录)
select 字段名列表 from 表A left join 表B on 匹配条件;
select * from t1 left join t2 on t1.uid=t2.uid;
(2)右连接查询(当匹配条件成立时 以右表为主显示查询记录)
select 字段名列表 from 表A right join 表B on 匹配条件;
select * from t1 right join t2 on t1.uid=t2.uid;
未经允许不得转载:天府数据港官方信息博客 » Mysql之多表查询
客官点个赞呗! (0)