sqlite 子查询——迹忆客-ag捕鱼王app官网
子查询或称为内部查询、嵌套查询,指的是在 sqlite 查询中的 where 子句中嵌入查询语句。
一个 select 语句的查询结果能够作为另一个语句的输入值。
子查询可以与 select、insert、update 和 delete 语句一起使用,可伴随着使用运算符如 =、<、>、>=、<=、in、between 等。
以下是子查询必须遵循的几个规则:
- 子查询必须用括号括起来。
- 子查询在 select 子句中只能有一个列,除非在主查询中有多列,与子查询的所选列进行比较。
- order by 不能用在子查询中,虽然主查询可以使用 order by。可以在子查询中使用 group by,功能与 order by 相同。
- 子查询返回多于一行,只能与多值运算符一起使用,如 in 运算符。
- between 运算符不能与子查询一起使用,但是,between 可在子查询内使用。
select 语句中的子查询使用
子查询通常与 select 语句一起使用。基本语法如下:
select column_name [, column_name ]
from table1 [, table2 ]
where column_name operator
(select column_name [, column_name ]
from table1 [, table2 ]
[where])
示例
假设 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
现在,让我们检查 select 语句中的子查询使用:
sqlite> select *
from company
where id in (select id
from company
where salary > 45000) ;
结果如下:
id name age address salary
---------- ---------- ---------- ---------- ----------
4 mark 25 rich-mond 65000.0
5 david 27 texas 85000.0
insert 语句中的子查询使用
子查询也可以与 insert 语句一起使用。insert 语句使用子查询返回的数据插入到另一个表中。在子查询中所选择的数据可以用任何字符、日期或数字函数修改。
基本语法如下:
insert into table_name [ (column1 [, column2 ]) ]
select [ *|column1 [, column2 ]
from table1 [, table2 ]
[ where value operator ]
示例
假设 company_bkp 的结构与 company 表相似,且可使用相同的 create table 进行创建,只是表名改为 company_bkp。现在把整个 company 表复制到 company_bkp,语法如下:
sqlite> insert into company_bkp
select * from company
where id in (select id
from company) ;
update 语句中的子查询使用
子查询可以与 update 语句结合使用。当通过 update 语句使用子查询时,表中单个或多个列被更新。
基本语法如下:
update table
set column_name = new_value
[ where operator [ value ]
(select column_name
from table_name)
[ where) ]
示例
假设,我们有 company_bkp 表,是 company 表的备份。
下面的实例把 company 表中所有 age 大于或等于 27 的客户的 salary 更新为原来的 0.50 倍:
sqlite> update company
set salary = salary * 0.50
where age in (select age from company_bkp
where age >= 27 );
这将影响两行,最后 company 表中的记录如下:
id name age address salary
---------- ---------- ---------- ---------- ----------
1 paul 32 california 10000.0
2 allen 25 texas 15000.0
3 teddy 23 norway 20000.0
4 mark 25 rich-mond 65000.0
5 david 27 texas 42500.0
6 kim 22 south-hall 45000.0
7 james 24 houston 10000.0
delete 语句中的子查询使用
子查询可以与 delete 语句结合使用,就像上面提到的其他语句一样。
基本语法如下:
delete from table_name
[ where operator [ value ]
(select column_name
from table_name)
[ where) ]
示例
假设,我们有 company_bkp 表,是 company 表的备份。
下面的实例删除 company 表中所有 age 大于或等于 27 的客户记录:
sqlite> delete from company
where age in (select age from company_bkp
where age > 27 );
这将影响两行,最后 company 表中的记录如下:
id name age address salary
---------- ---------- ---------- ---------- ----------
2 allen 25 texas 15000.0
3 teddy 23 norway 20000.0
4 mark 25 rich-mond 65000.0
5 david 27 texas 42500.0
6 kim 22 south-hall 45000.0
7 james 24 houston 10000.0