简介
SQL–结构化查询语言,也是一种关系型数据库管理系统的标准语言。
其用途是用于存取数据及查询、更新、管理DBMS。
创建表
create table 表名(字段名 字段类型 [约束],...);
字段类型:
integer 整型
real 实型
text 文本类型
null 空类型
blob 二进制类型
常用的约束:
primary key 主键 唯一的标识表中的一行数据
not null 不为空
unique 唯一
check 检查
default 默认值
修改表
修改表的名称:
alter table 表名 rename to 新名字;
增加字段:
alter table 表名 add column 新增加字段名 字段类型 [约束];
注:
其它的方式修改表结构:
1.把原来的表改个名字
alter table t_student rename to tmp;
2.新建一个需要的表
create table t_stu(sno integer primary key,sname text not null,sage integer check(sage>6),saddr text default "cs");
3.把原来表中的内容插入到新表中
insert into t_stu select * from tmp;
4.把原来的表删掉
drop table tmp;
删除表
drop table 表名;
数据操纵语言:DML
增
insert into 表名 values(字段值,...);
insert into 表名(字段名,...) values(字段值,...);
例如:
insert into t_student values(1002,"zhangfei",7,"CN");
insert into t_student(sno,sname,sage) values(1003,"zhangfei",7);
删
delete from 表名 where 条件;
条件:
字段名 运算符 值
注:
and/or 可在where子句中连接多个条件
例如
delete from t_student where sno=1001;
运算符:
> < >= <= <> != =
改
update 表名 set 字段=新值,... where 条件;
查
select 字段名1,字段名2,...from 表名 where 条件;
select sno,sname,sage,addr from t_student;
select * from 表名;
高级查询
1.模糊查询
like
SQL通配符:% _
%:替代一个或多个字符
_:替代一个字符
例:
select * from t_stu where sname like "zhang%";
select * from t_stu where sname like "zhang_";
between
在某个范围之内
列名 between v1 and v2;
包括 v1 和 v2
2.限定排序
限定limit和offset
select * from t_stu limit 2;//只显示前面两行
select * from t_stu limit 1,3;//从第一行后面开始显示3行数据
select * from t_stu limit 3 offset 1;//从第一行后面开始显示3行数据
排序:order by (升序 asc,降序 desc)
select * from t_stu order by sno desc/asc;
限定+排序
select * from t_stu order by sno desc limit 1;
3.常用函数
sum()
avg()
select avg(sage) as 平均值 from t_stu ;//as 给字段起别名
count()
min()
max()
abs()
length()
upper()
lower()
4.分组 group by
select sno,avg(score) from t_score group by sno;
5.去重复 distinct
select distinct sno from t_score;
6.多表连接
select t_score.sno,sname,score from t_stu,t_score where score=100 and t_stu.sno=t_score.sno;
//查询分数为100分的学生的学号、姓名、成绩
7.子查询
select 1 in(1,2,3);
select count(*) from t_stu where sno in(select sno from t_stu where sname="aaa" or sname="bbb");
select sno from t_stu where sname="aaa" or sname="bbb";-->(1001,1002);