教程 > postgresql 教程 > 阅读:123

postgresql like 子句——迹忆客-ag捕鱼王app官网

在 postgresql 数据库中,我们如果要获取包含某些字符的数据,可以使用 like 子句。

在 like 子句中,通常与通配符结合使用,通配符表示任意字符,在 postgresql 中,主要有以下两种通配符:

  • 百分号 %
  • 下划线 _

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

如果没有使用以上两种通配符,like 子句和等号 = 得到的结果是一样的。

语法

以下是使用 like 子句搭配百分号 % 和下划线 _ 从数据库中获取数据的通用语法:

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

你可以在 where 子句中指定任何条件。可以使用 and 或者 or 指定一个或多个条件。xxxx 可以是任何数字或者字符。

示例

下面是 like 语句中演示了 % 和 _ 的一些差别:

序号 例子 描述
1 where salary::text like '200%' 找出 salary 字段中以 200 开头的数据。
2 where salary::text like ' 0%' 找出 salary 字段中含有 200 字符的数据。
3 where salary::text like '_00%' 找出 salary 字段中在第二和第三个位置上有 00 的数据。
4 where salary::text like '2 % %' 找出 salary 字段中以 2 开头的字符长度大于 3 的数据。
5 where salary::text like '%2' 找出 salary 字段中以 2 结尾的数据
6 where salary::text like '_2%3' 找出 salary 字段中 2 在第二个位置上并且以 3 结尾的数据
7 where salary::text like '2___3' 找出 salary 字段中以 2 开头,3 结尾并且是 5 位数的数据

在 postgresql 中,like 子句是只能用于对字符进行比较,因此在上面例子中,我们要将整型数据类型转化为字符串数据类型。

创建 company 表( ),数据内容如下:

jiyik_db=# select * from company;
 id | name  | age | address   | salary
---- ------- ----- ----------- --------
  1 | paul  |  32 | california|  20000
  2 | allen |  25 | texas     |  15000
  3 | teddy |  23 | norway    |  20000
  4 | mark  |  25 | rich-mond |  65000
  5 | david |  27 | texas     |  85000
  6 | kim   |  22 | south-hall|  45000
  7 | james |  24 | houston   |  10000
(7 rows)

下面实例将找出 age 以 2 开头的数据:

jiyik_db=# select * from company where age::text like '2%';

结果如下:

id | name  | age | address     | salary
---- ------- ----- ------------- --------
  2 | allen |  25 | texas       |  15000
  3 | teddy |  23 | norway      |  20000
  4 | mark  |  25 | rich-mond   |  65000
  5 | david |  27 | texas       |  85000
  6 | kim   |  22 | south-hall  |  45000
  7 | james |  24 | houston     |  10000
  8 | paul  |  24 | houston     |  20000
(7 rows)

下面实例将找出 address 字段中含有 - 字符的数据:

jiyik_db=# select * from company where address  like '%-%';

结果如下:

id | name | age |                      address              | salary
---- ------ ----- ------------------------------------------- --------
  4 | mark |  25 | rich-mond                                 |  65000
  6 | kim  |  22 | south-hall                                |  45000
(2 rows)

查看笔记

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