单表查询与多表查询

表与表—拷贝 copy_table

复制表 copy_table  (自动增长,主键不能跟着拷贝过去)
全部拷贝
create table copy_table select * from t1; 
只拷贝表结构
    create table copy_table slelect * from t1 where 1 < 0
 

记录的增删改查

记录的增删改查
增: insert [ into ] 表明 value/values(字段1,字段2,……)
删除:delete from t1 [ where id > 5 ]; 

改:(只能修改同一行多个值)
update 表名 set name = ‘zxx’ where id = 5;

完整的建表语句

完整的表查询语句
select [ distinct ] * 或 字段名 或 聚合函数 或 表达式 from 表明  [
where 条件
group by 分组
having 分组在过滤
order by 排序
limity 控制显示的条数
 ]distinct 去除重复
* 是所有字段名 
表达式:加减乘除

 where 约束

关键字介绍 where  (注意:where中不能有聚合函数!!!)

where 是一个硬盘读取数据的过滤条件

支持的运算符:

         (1) 比较运算符<  >  <=  >=  !=

         (2) between 80 and 100

         (3) in(80,90,100)

         (4) like ‘%s wxx %s’       % :代表任意多字符  _ : 一个字符 

         (5) 逻辑运算符  and not or

 group by 分组

group by 分组 (一般与聚合函数一起用)
将所有记录按某个字段归类
生活中方便管理
数据库中方便统计

语法:select * from 表名 group by sex 这样查的结果是每个组的第一条记录没有意义
    所以我们要设置set global sql_mode='ONLY_FULL_GROUP_BY';
    注意设置好,只显示 group by 的一列
这样设置以后我们就要跟聚合函数一起用
语法:select sex,count(sex) from emp group by sex;

聚合函数
max() /min() 求最大值和求最小值
avg()   求平均数
sum()  求和
count() 次数
group by 与 聚合函数

having 过滤

having 过滤 (与group by 一起出现)
过滤等级 wheregroup byhaving 

group by 发生在were 之后
having 发生在 group by 之后

能使用聚合函数
能使用字段名

语法:select dept,avg(salary) from emp group by dept having avg(salary) > 5000;

order by 排序

order by 排序  [desc降序,asc升序]
对记录进行排序,默认升序
语法 select * from emp order by salary [ asc ];

limit 限制记录显示条数

limit 限制记录显示条数
limit m.n  表示从m+1条开始显示n 条记录
m可以不写,默认为是0    
语法: select * from emp limt 23select * from emp order by salary desc limit 1;

多表查询

( 一 )笛卡尔积查询

1 笛卡尔积查询
用坐标中的一条记录去连接另一张表的所有记录
产生大量无用数据

语法: select * from emp,dept where enp.dep_id = dept.id;

on 关键字

用于多表查询,进行条件限制

(二)内连接查询  inner join

2 内连接查询 inner join    (后面可以用on 做条件限制)
语法:select * from emp,dept on enp.dep_id = derp_id;

(三) 左外连接 left join

3 左外连接查找 left join
左边完全显示,右边匹配上数据才显示
select * from left join emp,dept on enp.dep_id = dept.id;

(四) 右外连接 right join

4 右外连接 right join
右边完全显示,左边匹配上数据才显示
select * from right join emp,dept on enp.dep_id = dept.id;

(五) 全外连接 union 与 union all 区别

5 全外连接 unionunion all(注意:合并表的结果必须一模一样!!!)
就是把多个表合并到一起显示
union 默认去重
union all 不去重 

语法:
select * from dept left join emp on enp.dep_id = dept.id 
union
select * from dept right join emp on enp.dep_id = dept.id;

理论上可以合并多张表
select * from dept left join emp left join xxable on enp.dep_id = dept.id union 

(六)子查询

6 子查询
将上一次查询的结果作为本次查询的数据(或者判断条件)
语法:
select * from emp where salary = (select max(salary) from emp); 
原文地址:https://www.cnblogs.com/liu--huan/p/9647829.html