sqlite3简要学习笔记

sqlite3虽然已接触已大半年,但是偶尔浏览别人的sqlite语法,顿时觉得自己掌握得不扎实,只得进一步加强
一:格式 sqlite3创建表时讲究简洁明了,格式统一;一栏colume占一排,而非一排一排写完再写下一条。
最初的格式:
create table users(ID varchar(38) NOT null,NAME varchar(20) NOT null,Account .....,UType INT not null default '0',primary key(ID));
改进的格式:
create table users(
ID varchar(38) NOT null,
Name varchar(20) NOT null,
Account .....,
UType INT not null default '0',
primart key(ID) --(1)
);
二:部分注解
1:varchar(38)代表可变长度字符向量(字符数组),最大长度限制为38;如果是char(38)是不可变的,始终占38byte
2:not null 对column名的修饰则意为:约束记录不能为空,否则报错。
3:not null后跟default '0'意为:设该column的默认值为'0'。
4:(1)处表示主键的另一种书写方式,即primary key(column name),主键值必须唯一。
5:建立索引可以优化数据的查找,当需要在大数据中进行查找时建立索引十分有用。建立索引的语法为:create (unique) index index_name on table_name(column_name);
三:补充
6: 我们都知道查询数据库像这样用:select * from table_name where column_name = XXX;
查询并将查询结果排序输出则需要加order by,像这样:select * from table_name order by column_name;
这样查询输出的顺序是默认以column_name的字符按升序(asc)输出的,因此在column_name后加asc的效果与不加是一样的。
如果要降序输出(desc),即从大到小输出,则加desc修饰即可。
7:查询一个表的数据条数:select count(*) from table_name;
8:限制输出条数:select * from table_name limit val;
9:添加数据记录
insert into table_name(field1, field2, ...) values(val1, val2, ...);
valx为需要存入字段的值。
例,往学生信息表添加数据:
Insert into student_info(stu_no, name) values(0001, alex);
10:修改数据记录
update table_name set field1=val1, field2=val2 where expression;
where是sql语句中用于条件判断的命令,expression为判断表达式
例,修改学生信息表学号为0001的数据记录:
update student_info set stu_no=0001, name=hence where stu_no=0001;
11:删除数据记录
delete from table_name [where expression];
不加判断条件则清空表所有数据记录。
例,删除学生信息表学号为0001的数据记录:
delete from student_info where stu_no=0001;
12:UNIQUE - 唯一:
除主键外,约束其他列的数据的值唯一
13:CHECK - 条件检查:
约束该列的值必须符合条件才可存入
create table user(
name text,
id unique check text,
pssword text,
primary key(name)
);
14:删除表,删除索引
drop table table_name;
drop index index_name;
15:几张表联查
一:
select * from A where id in(select top 1 id from B order by time desc );
上面这句的动作是:先对b表进行降序排序并输出第一个id,以这个id作为条件再去a表中查询。select * from table_a where id in(select top 1 id from b order by time desc);
二:
select a.id,a.name,b.time from a,b where a.id=b.id;
上面这句的动作是:联合a表和b表,输出两表中id相等的部分的id,name和time三个column。select table_a.column_a,table_b.column_b from table_a,table_b where table_a.column_a=table_b.column_b。
浙公网安备 33010602011771号