sql语句的使用经验 postgresql

查找指定字段为空或不为空

查询数据库中指定字段为空的行数据:

select * from tablename where columnName = '';  字符串类型可以用 '' ,也可以用Null

select * from tablename where is Null(columnName); 可以用来指定int类型

查询不为空数据:

select * from tablename where columnName <> '';    <>不等于

select * from tablename where columnName != '';

将查询的数据插入新的表

insert into [表名] select * from [表名] where ...

数据库内字段数据处理:

一、向原有的数据添加数据

update [表名] set column = concat("str",columnName(需要添加数据的字段名));

二、合并列数据

1.先新建一个字段用来存放合并后的数据

2.用concat合并,并赋给新建的列

alter table [表名] add column [字段名] [类型];

update [表名] set [新建的字段] = concat([原有字段1], [原有字段2]);

两种表复制:insert into from和select into from

一般insert into [table1] select,用于将select选择的数据插入到另一张表中

select [字段1[,字段2...]] into [table] from  ,用于将选择的数据插入新表中

regexp_matches的用法以及取出数组中的值

函数:regexp_matches(string text, pattern text [, flags text])
说明:Return all captured substrings resulting from matching a POSIX regular expression against the string. See Section 9.7.3 for more information. 对字符串按正则表达式进行匹配,如果存在则会在结果数组中表示出来
例子:regexp_matches('foobarbequebaz', '(bar)(beque)') = {bar,beque}

但是如何取出数组中的值呢?

(select regexp_matches())[1] 

如果直接将数组返回赋给一个值则会出现出错?

即返回多行的函数的错误

update xzcf set 处罚类别=regexp_matches(处罚类别, '.{2}') where id=1;    

报错:   [Err] 错误:  set-returning functions are not allowed in UPDATE

原因:regexp_matches()会返回一个数组(多行)

对于返回多行的函数,如果在where条件中执行过滤,会返回如下错误。

ERROR:  0A000: set-returning functions are not allowed in WHERE  

如果要创建基于SRF函数(即返回多行的函数)的表达式索引,会报如下错误:

ERROR:  0A000: set-returning functions are not allowed in index expressions 

 

一行变多行

方法一、 unnest(数组,分隔符)

select [col1],unnest(string_to_array([col2],'分隔符')) from [table];

方法二、regexp_split_to_table(字符串,分隔符)

select [col1],regexp_split_to_table([col2],'分隔符') from [table];

原文地址:https://www.cnblogs.com/holden1/p/9930737.html