数据库学习SQLite (一)
1.多层选择语句:
select name from (select name,tel_no from (select *from students) ) ;
2.联表查询,使用as省略部分代码:
select cls.major as cmj, students.name from classes as cos, students where cls.id = 2 and cos.year >2008;
3.group by: 将得到的结果集按照一定的规则划分为多个组。
select count(*) ,cls_id from students group by cls_id having cls_id>2;
将cls_id 大于2 的进行分组
4.order by 升序asc 降序 desc
select * from students order by cos_id desc ,name asc;
5. 分页加载数据:
select * from students limit 1 offset 2;--》select * from students limit 2,1;
从索引为3 的记录开始索引,并且只返回其中1条数据
6.去重 distinct
select distinct * from students ;
7.多表查询
select * from students ,classes where students.cls_id = classes.id;
==>内链接 select * from inner join classes on students.cls_id = classes.id;
两者的功能一致,只是内链接添加了inner join 关键字, 并且用on 取代where.
==>左外链接 select * from left outer join classes on students.cls_id = classes.id;
内链接:只有符合条件的一条数据才显示,否则不显示
左外链接:以左表students为基准,右表classes 中数据为空时显示空值并填充。
(Android只支持这两种,右外链接:以右侧表为基准。全外链接:有任何一方存在不匹配数据则用空值填充。但是对于SQLite来说,它只支持内链接和左外链接)
8.update 更新语句
update students set tel_no =4232, cls_id =3 where name= 'jake' ;
9.delete 删除语句
delete from students where cls_id = 2;
10.修改表 alter
alter table tableName {rename to newName | add column 新的字段}
重命名表结构:(1) alter table students rename to stu_newtable;
添加表字段: (2) alter table students add column age integer default 0;
修改表字段:(3) alter table students change oldcolumn newcolumn typecolumn
删除表字段:麻烦,所以尽量增加的时候注意。
CREATE TABLE 'stu_temp' (
'id' integer PRIMARY KEY AUTOINCREMENT,
'name' varchar(20) CHECK (length (name) >3),
'tel_no' varchar (11) NOT NULL,
'cls_id' integer NOT NULL
);
insert into stu_temp select id ,name ,tel_no,cls_id from students;
drop table students;
alter table stu_temp rename to students;
(1)创建一个stu_temp新表、
(2)将students中的数据导入到stu_temp 中,
(3)删除 students 表,
(4)将stu_temp命名为students