教程 > sqlite 教程 > 阅读:217

sqlite like 语句——迹忆客-ag捕鱼王app官网

sqlite 的 like 运算符是用来匹配通配符指定模式的文本值。如果搜索表达式与模式表达式匹配,like 运算符将返回真(true),也就是 1。这里有两个通配符与 like 运算符一起使用:

  • 百分号 (%)
  • 下划线 (_)

百分号(%)代表零个、一个或多个数字或字符。下划线(_)代表一个单一的数字或字符。这些符号可以被组合使用。


语法

% 和 _ 的基本语法如下:

select column_list 
from table_name
where column like 'xxxx%'
-- 或者
select column_list 
from table_name
where column like '%xxxx%'
-- 或者
select column_list 
from table_name
where column like 'xxxx_'
-- 或者
select column_list 
from table_name
where column like '_xxxx'
-- 或者
select column_list 
from table_name
where column like '_xxxx_'

我们可以使用 and 或 or 运算符来结合 n 个数量的条件。在这里,xxxx 可以是任何数字或字符串值。

示例

下面一些示例演示了 带有%_ 运算符的 like 子句不同的地方:

语句 描述
where salary like '200%' 查找以 200 开头的任意值
where salary like ' 0%' 查找任意位置包含 200 的任意值
where salary like '_00%' 查找第二位和第三位为 00 的任意值
where salary like '2_%_%' 查找以 2 开头,且长度至少为 3 个字符的任意值
where salary like '%2' 查找以 2 结尾的任意值
where salary like '_2%3' 查找第二位为 2,且以 3 结尾的任意值
where salary like '2___3' 查找长度为 5 位数,且以 2 开头以 3 结尾的任意值

让我们举一个实际的例子,假设 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

下面示例显示 company 表中 age 以 2 开头的所有记录:

sqlite> select * from company where age  like '2%';

结果如下:

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       85000.0
6           kim         22          south-hall  45000.0
7           james       24          houston     10000.0

下面示例显示 company 表中 address 文本里包含一个连字符(-)的所有记录:

sqlite> select * from company where address  like '%-%';

结果如下:

id          name        age         address     salary
----------  ----------  ----------  ----------  ----------
4           mark        25          rich-mond   65000.0
6           kim         22          south-hall  45000.0

查看笔记

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