暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

PostgreSQL 表达式索引 - 语法注意事项

digoal 2016-08-03
320

作者

digoal

日期

2016-08-03

标签

PostgreSQL , 表达式索引 , 括号


背景

表达式索引是非常有用的功能之一,但是使用时语法上要注意一下,表达式需要用括号括起来

```
expression

An expression based on one or more columns of the table. The expression usually must be written with surrounding parentheses, as shown in the syntax. However, the parentheses can be omitted if the expression has the form of a function call.
```

仅仅当表达式是单一的函数时,不需要括号。

例子

如果表达式不是函数,则会有这样的错误

```
postgres=# create table t2(c1 text, c2 text);
CREATE TABLE

postgres=# create index idx1_t2 on t2 (c1||c2);
ERROR: 42601: syntax error at or near "||"
LINE 1: create index idx1_t2 on t2 (c1||c2);
^
LOCATION: scanner_yyerror, scan.l:1081
```

报错的原因是语法不支持。

解决办法,表达式用括号括起来

postgres=# create index idx1_t2 on t2( (c1||c2) ); CREATE INDEX

类似的例子还很多

```
postgres=# create index idx1_t4 on t2 (c1::int);
ERROR: syntax error at or near "::"
LINE 1: create index idx1_t4 on t2 (c1::int);
^

postgres=# create index idx1_t3 on t2 ((c1::int));
CREATE INDEX

postgres=# create index idx1_t5 on t2 ( substring(c1,1,2) || 'abc' );
ERROR: syntax error at or near "||"
LINE 1: create index idx1_t5 on t2 ( substring(c1,1,2) || 'abc' );
^
postgres=# create index idx1_t5 on t2 ( (substring(c1,1,2) || 'abc') );
CREATE INDEX
```

PostgreSQL 许愿链接

您的愿望将传达给PG kernel hacker、数据库厂商等, 帮助提高数据库产品质量和功能, 说不定下一个PG版本就有您提出的功能点. 针对非常好的提议,奖励限量版PG文化衫、纪念品、贴纸、PG热门书籍等,奖品丰富,快来许愿。开不开森.

9.9元购买3个月阿里云RDS PostgreSQL实例

PostgreSQL 解决方案集合

德哥 / digoal's github - 公益是一辈子的事.

digoal's wechat

文章转载自digoal,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论