首先看一下sqlite的增,删,查,改的基本用法。
1. 查 select
select * from table_name
or
select key1, key2 from table_name
2. 增 insert
insert into table_name values (value1, value2, ....)
or
insert inot table_name (key1, key2) values (values1, values2)
3. 改 update
update person set key=value //对整个表的key列进行更新
or
update person set key1=value1 where id=21
4. 删 delete
delete from table_name where id=1
其次让增删改查更加有效
1. where
select * from table_name where age>21
查找表中age大于21的数据,当然用age这里仅为举例
select * from table_name where age>21 and age < 24
查找age在区间(21,24)的数据 ,要达到这个目的还可以用between
select * from table_name where age between 21 and 24
select * from table_name where age in (21,22,27)
查找age=21,22或者27的数据 ,in在这里提供了一个取值的集合
select * from table_name where name like 'zhang%'
具体都支持那些通配符可以到baidu了解一下
selete * from table_name where age is null
如果是检索没有设置age的数据,那就要用到is null来判断
2. order by
select * from table_name order by id desc
按照id降序排列,默认的检索结果是按照升序排列的
select * from table_name order by name desc , age asc
按照name降序排列,name相同的按照age升序排列
3. join
3.1 cross jon
select table1.key1, table2.key2 from table1 cross join table2
这时table1中的每一行都会和table2中的数据进行组合,然后输出
3.2 inner jon
select table1.key1, table.key2 from table1 inner join table2 on table1.id1=table2.id2
这时table1中的每一样会和table2中的每一行数据进行匹配,如果按照判断表达式匹配成功则输出该数据
如果table1和table2中匹配条件中所用的列名相同,还可以使用using,在匹配条件较多时,使用using是比较方便的
selete table1.key1, table2.key2 from table1 inner join table2 using (id)
3.3 outer join 对于outer join ,sqlite仅支持left outer join
selete table1.key1, table2.key2 from table1 left outer join table2 on table1.id1=table2.id2
和inner join 不同的是outer join table1中的每一行会和table2中的每一行进行匹配,如果匹配成功则输出table2相应的数据,如果匹配不成功,则数据null,这样以来table2中的数据无论如何都会全部输出的
4. as
as用来对表名或者列名取别名,这在表名太长的时候是比较方便的,比如在使用join时,反复使用的表名。另外在同一张表做join处理时产生了命名冲突,也需要使用as来处理,还有一些函数结果输出的时候,可以用as取一个临时列名
select t1.key1, t2.key2 from table1 as t1 cross join table2 as t2
select sum(page) age count from table_name
5. union
如果两组需要输出的数据具有相同的列数,并且对应列的数据类型也是相同的,则可以使用union把两个结果集合在一次select结果中输出
select table1.key1, table1.key2 from table1
union
select table2.key1, table2.key2 from table2
但是这个时候两个结果中相同的数据仅被输出一次,如果需要全部输出,则使用union all
6. limit
selete * from table_name limit 1
仅输出检索结果中的第一条数据
selete * from table_name limit 2, 2
输出检索结果中除前两条数据后的前两条数据,即第三,第四条数据
7. group by
对具有某些相同属性的行进行分组,这个大都是为了计算,如对分组数据进行求和或者平均值等
select count(id) as count from table_name group by age
根据年龄进行分组,计算相同年龄的人数
8. haveing
和where不同,where是对列进行条件筛选,而having是和group by搭配使用,对分组后的结果进行筛选,确定那些分组可以被输出的结果中
select count(id) as count from table_name group by age having count > 1
只有人数大于1人的分组才可以输出
9. distinct
select distinct * from table_name
和直接用select不同,加了distinct后重复的数据只会输出一次
10. view 在sqlite里,view是只读的
create view view_name as
selelect key1, key2, key3 from table_name
view 可以方便的用来显示某一个表的子集,或者多个表进行某些复杂的select后的结果
Sqlite 学习笔记
最新推荐文章于 2023-05-22 22:44:48 发布