常用sql语句

来源:互联网 发布:mac笔记本切换输入法 编辑:程序博客网 时间:2024/06/04 23:31
建表:
create table t_student(id integer, name text, age integer, score real);

create table if not exists t_student(id integer, name text, age integer, score real);

删表:
drop table t_student;

drop table t_student if exists;

插入数据:
insert into t_student (name, age) values (‘zhangsan’, 22);

注意:字符串应该用单引号

更新数据:
将t_student这张表中所有的name改为jack,age改为20:
update t_student set name=‘jack’,age=20;

将name为jack的score改为99
update t_student set score=99 where name=‘jack’;


删除表中数据:
删除表中所有数据:
delete from t_student;

删除name为tom的这条数据
delete from t_student where name=‘tom’;


条件语句格式:
“where 字段 = 某个值”
“where 字段 is 某个值” // “is”相当于”=“
“where 字段 != 某个值“
“where 字段 is not 某个值” // “is not”相当于”!=“
“where 字段 > 某个值”
“where 字段1 = 某个值 and 字段2 > 某个值”
“where 字段1 = 某个值 or 字段2 = 某个值”  


查询:
select * from t_student;// 查询所有字段

select name, age from t_student;// 查询某些字段

select * from t_student where age > 10;// 条件查询


起别名:
select name myname ,age myage from t_student;
//给name起个叫做myname的别名,给age起个叫做myage的别名

select s.name, s.age from t_student s;
// 给t_student表起个别名叫做s,利用s来引用表中的字段


计算记录的数量:
// 共有多少个学生
select count(age) from t_student;
// score>=60的学生有多少
select count(*) from t_student where score >= 60;


排序:
select * from t_student order by age asc;// 升序

select * from t_student order by age desc;// 降序

select * from t_student order by age asc, score desc;
// 先按age升序排,如果age相等按score降序排


limit:
select * from t_student limit 4, 8;

// 跳过前面4条数据,然后取8条数据


select * from t_student limit 7;
// 这句相当于:select * from t_student limit 0, 7;

limit常用来做分页查询,比如每页固定显示5条数据,那么应该这样取数据:
第一页:limit 0, 5
第二页:limit 5, 5
第三页:limit 10, 5

第n页:limit 5*(n-1), 5


简单约束:
建表时可以给特定的字段设置一些约束条件,常见的约束有:
not null:规定字段的值不能为空
unique:规定字段的值必须唯一
default:指定字段的默认值

create table t_student(id integer, name text not null unique, age integer not null default 1);
// name字段不能为空,并且唯一
// age字段不能为空,默认值为1



主键约束:
主键:用来唯一标识某一条记录
主键应当是对用户没有意义的
永远也不要更新主键
主键不应包含动态变化的数据
主键应当由计算机自动生成

create table t_student(id integer primary key, name text, age integer);
// 如果某个字段是主键,该字段默认包含了not null 和 unique两个约束

create table t_student(id integer primary key autoincrement, name text, age integer);
// 自动增长的主键

0 0
原创粉丝点击