======================= 数据行操作 ===================
1、增
insert into 表 values (值,值,值); # 必须一一对应
insert into 表 (列名,列名...) values (值,值,值...); # 根据键对应
insert into 表 (列名,列名...) values (值,值,值...),(值,值,值...) # 插入多个值
insert into 表 (列名,列名...) select 列名,列名... from 表 [where xxx]; # 必须格式对应
2、删
delete from 表; 清空表
truncate table tb1; 清空表,速度快,自增回到原点
delete from 表 where id=1 and name='alex';
3、改
update 表 set name = 'alex' where id>1;
4、查
select id.name from tb;
select * from tb [条件] [限制] [排序] [分组];
select * from user\G; # 格式化输出所有信息,(无\G,会因为数据过多而乱序)
5、条件
> < >= <= = != in like not % _ between and or
where nid>1 and name!='alex';
where nid between 5 and 10; # [5, 10]
where nid [not] in(1,2,12);
where nid in select nid from 表;
where name like 'a%'; # a开头,后面多个字符
where name like 'a_'; # a开头,后面一个字符
6、分页
limit 5; # 第0行开始,后面5行
limit 3,10; # 第3行开始,后面10行
limit 10 offset 3; # 取10行,从第3行开始(偏移量为3)
7、排序
order by nid; # 默认增序
order by nid asc|desc; # 指定顺序 增|减
order by nid desc, name desc; # 两个权重列
8、分组
select num from 表 group by num # 必须对应
select num,nid from 表 group by num,nid
select num,nid from 表 where nid > 10 group by num,nid order by nid desc
select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid
select age,count(nid) as '个数', max(nid) as '最大nid' from 表 group by age;
select num,count(nid) as '个数' from 表 group by num having max(nid) > 10
特别的:
group by 必须在where之后,order by之前
分组筛选用的是 having,不在是where
9、组合
组合,自动处理重合
select nid,name from tb1
union
select nid,name from tb2;
组合,不处理重合
select nid,name from tb1
union all
select nid,name from tb2;
必须所选内容全部一致 才叫重合
10、连表
笛卡尔积
select * from tb1,tb2;
结果是 tb1 * tb2
where
无对应关系则不显示
select tb1.nid, tb1.name, tb2.name
from tb1,tb2
where tb1.nid = tb2.nid;
inner [outer] join 交集
无对应关系则不显示
select tb1.nid, tb1.name, tb2.name
from tb1 inner join tb2
on tb1.nid = tb2.nid;
left [outer] join 交集,左为主
A表所有显示,如果B中无对应关系,则值为null
select tb1.nid, tb1.name, tb2.name
from tb1 left join tb2
on tb1.nid = tb2.nid;
right join 交集,右为主
B表所有显示,如果A中无对应关系,则值为null
select tb1.nid, tb1.name, tb2.name
from tb1 right join tb2
on tb1.nid = tb2.nid;
并集
通过 left join union right join 间接实现
11、函数
select FUN(列名) from 表名 [where condition..];
FUN: 平均avg/ 求和sum/ 最大值max/ 统计count