### 增删改查
基本sql语句(增,删,改,查)
库操作:
> show databases; #列出
> create database db1; #创建
> show create database db2; #查看属性
> drop database db2; #删除
> use db1; #切换库
表操作: use db1; #进库的前提
> show tables; #列出当前库中所有的表
> create table t1 (id int(10),name char(10)); #创建表,至少要有一个字段,多个字段用","隔开
> desc t1; #查看表结构
> show create table t10\G #查看表的创建属性
> alter table t1 rename to t10; #修改表名
> alter table t1 add sex char(10); #添加字段在末位
> alter table t1 add QQ int after name; #添加字段在指定字段的后面
> alter table t1 add uid int first; #添加字段在首位
> alter table t1 drop uid; #删除字段
> alter table t1 change id uid int; #修改字段的名称及属性
> alter table t1 modify uid int(10); #只修改字段uid的属性
> drop table t2; #删除表
记录操作: and ↔ && or ↔ || not ↔ !
insert into t1 values();
> insert into t1 set uid=1,name='tom',sex='male'; #添加一条记录
> insert into t1 (uid,name,sex) values (2,'jim','male'); #添加一条记录
> insert into t1 (uid,name,sex) values (3,'lilei','male'),('4','lily','female'); #添加多条记录
> insert into t1 values (5,'lucy',123,'female'); #注意:列数和值数一定要一样
> update t1 set name='hanmeimei' where uid=6; #修改记录,注意定位
> update t1 set uid=6 where name='lucy' and QQ is null; #多条件定位
> delete from t1 where uid=6; #删除记录,注意定位
> truncate t1 ; #清空表的记录
单表查询: \G
> select * from t1; #查询表中所有字段的所有记录
> select name,qq from t1; #查询部分字段的所有记录
> select name,chinese from t2 where chinese >= 80; #查询部分字段的部分记录
> select name,chinese,english from t2 where chinese >= 80 and english = 100; #多条件定位
> select * from t2 order by chinese; #升序排列
> select * from t2 order by chinese desc; #desc: 逆序
> select * from t2 order by chinese desc limit 2; #只显示前几条记录
> select * from test_table limit 100 ,10; #分页查询
> select * from t2 where english=(select max(english) from t2); #子查询
> select * from t2 where name like 't%'; #模糊匹配 %: 所有 _: 单个字符
> select * from t2 where name regexp '^t'; #过滤
> select name,chinese+math+english as total from t2; #as别名(as可不写)
> select count(name) from t2; #统计name字段有多少记录, null不会被统计
> select count(1) from t2; #统计有多少条记录
> select count(*) from t2; #统计表中有多少条非空的记录
> select sex,count(sex) from t1 where score>=60 group by sex; #统计sex性别字段中相同的值的个数,当score分数大于60.
多表联合查询:
内连接: 两个表某字段的值完全一样
> select t1.name,t1.sex,t2.math from t1 join t2 on t1.name=t2.name;
> select t1.name,t1.sex,t2.math from t1,t2 where t1.name=t2.name;
外连接: 左,右连接
左: 显示出左表中所有的记录
右: 显示出右表中所有的记录
> select t1.name,t1.sex,t2.math from t1 left join t2 on t1.name=t2.name; #左连接
> select t2.name,t1.sex,t2.math from t1 right join t2 on t1.name=t2.name; #右连接
full join #全连接