本文是笔者记录的SQL操作的笔记。
constraint(表约束 & 列约束)
创建表时可以使用 constraint 来指定表约束,比如联合主键,也可以用来指定列约束,如下所示:
create table test_t (
id_1 integer not null, -- column constraint
id_2 integer,
constraint id2_notnull_constraint unique(id_2), -- column constraint
constraint multi_primary_constraint primary key(id_1 desc, id_2) -- table constraint
);on conflict clauses
创建表的时候,可以使用 on conflict 子句来指定当约束冲突的时候解决方案,如下所示:
适用于
unique,not null,check,primary key约束。
create table tab_on_conflict_abort (id int primary key unique on conflict abort , txt text);
create table tab_on_conflict_fail (id int primary key unique on conflict fail , txt text);
create table tab_on_conflict_ignore (id int primary key unique on conflict ignore , txt text);
create table tab_on_conflict_replace (id int primary key unique on conflict replace , txt text);
create table tab_on_conflict_rollback (id int primary key unique on conflict rollback, txt text);可以看到有五种解决方案,默认是 abort 方案。
count(*) & count(1) & count(column)
count()会找出表中不为NULL的行的数量。
count(column) 会检查每一行中的值是否为NULL,进行计数。
count(*,1,”everything”) 会表中不为NULL的行数,某一行所有列都为NULL时,这行会被忽略,所以实际上会在表中找到一列NOT NULL进行计数,同时会优先选择最短的索引以减少IO。
all distinct
select distinct col from table; -- 会忽略重复的行
select all col from table; -- 等于 select col from table,不会忽略重复的行子查询中也有一个all,此时的all表示全部满足才返回true,对应的any表示有任意一个满足就返回true,看下面的例子:
-- 查询01班级中,年龄大于02班所有人的同学
select * from student where class_no='01' and age > all(select age from student where class_no='02');
select * from student where class_no='01' and age > (select max(age) from student where class_no='02');
-- 查询01班级中,年龄大于02班任意一个人的同学
select * from student where class_no='01' and age > any(select age from student where class_no='02');
select * from student where class_no='01' and age > (select min(age) from student where class_no='02');limit
limit 返回有限行的数据,不过MySQL和Sqlite中limit还可以指定第二个参数,表示个数,这个时候第一个参数相等于一个偏移,如下所示:
select * from table limit 0, 5; -- 等于 select * from table limit 5
select * from table limit 5, 5; -- 返回第六行开始的5行数据select
join
需要查询的数据在多张表时,需要连接,各种连接的类型见下图:

同时下面的语句时等价的:
A LEFT JOIN B A LEFT OUTER JOIN B
A RIGHT JOIN B A RIGHT OUTER JOIN B
A FULL JOIN B A FULL OUTER JOIN B
A INNER JOIN B A JOIN B