教程 > sqlite 教程 > 阅读:14

sqlite null——迹忆客-ag捕鱼王app官网

sqlite 的 null 是用来表示一个缺失值的项。表中的一个 null 值是在字段中显示为空白的一个值。

带有 null 值的字段是一个不带有值的字段。null 值与零值或包含空格的字段是不同的,理解这点是非常重要的。


语法

创建表时使用 null 的基本语法如下:

sqlite> create table company(
   id int primary key     not null,
   name           text    not null,
   age            int     not null,
   address        char(50),
   salary         real
);

在这里,not null 表示列总是接受给定数据类型的显式值。这里有两个列我们没有使用 not null,这意味着这两个列可以为 null。

带有 null 值的字段在记录创建的时候可以保留为空。

示例

null 值在选择数据时会引起问题,因为当把一个未知的值与另一个值进行比较时,结果总是未知的,且不会包含在最后的结果中。假设有下面的表,company 的记录如下所示:

id          name        age         address     salary
----------  ----------  ----------  ----------  ----------
1           paul        32          california  20000.0
2           allen       25          texas       15000.0
3           teddy       23          norway      20000.0
4           mark        25          rich-mond   65000.0
5           david       27          texas       85000.0
6           kim         22          south-hall  45000.0
7           james       24          houston     10000.0

让我们使用 update 语句来设置一些允许空值的值为 null,如下所示:

sqlite> update company set address = null, salary = null where id in(6,7);

现在,company 表的记录如下所示:

id          name        age         address     salary
----------  ----------  ----------  ----------  ----------
1           paul        32          california  20000.0
2           allen       25          texas       15000.0
3           teddy       23          norway      20000.0
4           mark        25          rich-mond   65000.0
5           david       27          texas       85000.0
6           kim         22
7           james       24

接下来,让我们看看 is not null 运算符的用法,它用来列出所有 salary 不为 null 的记录:

sqlite> select  id, name, age, address, salary
        from company
        where salary is not null;

上面的 sqlite 语句将产生下面的结果:

id          name        age         address     salary
----------  ----------  ----------  ----------  ----------
1           paul        32          california  20000.0
2           allen       25          texas       15000.0
3           teddy       23          norway      20000.0
4           mark        25          rich-mond   65000.0
5           david       27          texas       85000.0

下面是 is null 运算符的用法,将列出所有 salary 为 null 的记录:

sqlite> select  id, name, age, address, salary
        from company
        where salary is null;

上面的 sqlite 语句将产生下面的结果:

id          name        age         address     salary
----------  ----------  ----------  ----------  ----------
6           kim         22
7           james       24

查看笔记

扫码一下
查看教程更方便
网站地图