iOSiOS菜鸟食谱

SQLite

2016-03-28  本文已影响278人  小盒盒

SQLite基础

1.简介

2.SQL 语句

3.DDL

示例
create table t_student (id integer, name text, age inetger, score real) ;
integer : 整型值
real : 浮点值
text : 文本字符串
blob : 二进制数据(比如文件)
create table t_student(name, age);
 - 为了保持良好的编程规范、方便程序员之间的交流,编写建表语句的时候最好加上每个字段的具体类型

4.DML

5.条件语句

6.DQL

    select 字段1, 字段2, … from 表名 ;
    select * from 表名;   //  查询所有的字段
    select name, age from t_student ;
    select * from t_student ;
    select * from t_student where age > 10 ;  //  条件查询
    格式(字段和表都可以起别名)
    select 字段1 别名 , 字段2 别名 , … from 表名 别名 ;
    select 字段1 别名, 字段2 as 别名, … from 表名 as 别名 ;
    select 别名.字段1, 别名.字段2, … from 表名 别名 ;
    示例
    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 (字段) from 表名 ;
    select count ( * ) from 表名 ;
    示例
    select count (age) from t_student ;
    select count ( * ) from t_student where score >= 60;

7.排序

   查询出来的结果可以用order by进行排序
   select * from t_student order by 字段 ;
   select * from t_student order by age ;
   默认是按照升序排序(由小到大),也可以变为降序(由大到小)
   select * from t_student order by age desc ;    //降序
   select * from t_student order by age asc ; // 升序(默认)
   也可以用多个字段进行排序
   select * from t_student order by age asc, height desc ;
   先按照年龄排序(升序),年龄相等就按照身高排序(降序)
   使用limit可以精确地控制查询结果的数量,比如每次只查询10条数据
   格式
   select * from 表名 limit 数值1, 数值2 ;
   示例
   select * from t_student limit 4, 8 ;
   可以理解为:跳过最前面4条语句,然后取8条记录
   limit常用来做分页查询,比如每页固定显示5条数据,      那么应该这样取数据
   第1页:limit 0, 5
   第2页:limit 5, 5
   第3页:limit 10, 5
   …
   第n页:limit 5*(n-1), 5
   猜猜下面语句的作用
   select * from t_student limit 7 ;
   相当于select * from t_student limit 0, 7 ;
   表示取最前面的7条记录

8.约束

   建表时可以给特定的字段设置一些约束条件,常见的约束
   not null :规定字段的值不能为null
   unique :规定字段的值必须唯一
   default :指定字段的默认值
    check;检查约束
   (建议:尽量给字段设定严格的约束,以保证数据的规范性
   示例
   create table t_student (id integer, name text not null unique, age integer not null default 1) ;
   name字段不能为null,并且唯一
   age字段不能为null,并且默认为1
  create table t_student (id integer primary key autoincrement, name text, age integer) ;

表连接查询

上一篇下一篇

猜你喜欢

热点阅读