Postgres SQL - 笔记

本文介绍了数据库中的递归查询技巧,包括根据父级ID查询子级和子级查询父级的方法,并展示了设置临时变量、时间格式转换、字符串操作及数学函数的使用。同时,提供了函数如SUBSTRING、TO_CHAR等的示例,以及如何创建游标进行跨库查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设置临时变量

set session “unit.name” to “张三”;

select current_setting(‘unit.name’)

更多:https://www.jb51.net/article/204214.htm

根据父级id,查询子级

with recursive cte as(select a.atid,cast(a.name as varchar(200)) from app_aqxj_equipment a where a.atid='5cbd1b00-ca0f-461c-9f13-2215bdaf1d9c'union all select k.atid,cast(c.name||'>'||k.name as varchar(200)) as name  from app_aqxj_equipment k inner join cte c on c.atid = k.parent_id--可以根据条件筛选where  k.type_id <> 'xunjianxiang')select atid,name from cte ;create or replace function func_get_loginUnit(in_userid varchar(200),out o_area text)
returns text as $$
DECLARE
 v_rec_record RECORD;
BEGIN
 o_area = '';
 FOR v_rec_record IN (WITH RECURSIVE r AS (
 SELECT userid,usertitle,userparentid,userwbscode FROM ta_users WHERE userid = in_userid
 union ALL
 SELECT ta_users.userid,ta_users.usertitle,ta_users.userparentid,ta_users.userwbscode FROM ta_users, r 
	WHERE ta_users.userid = r.userparentid and ta_users.userparentid <> '-1'
 )
SELECT userid,concat_ws(' > ',usertitle,'') as name,userparentid,userwbscode FROM r order by userwbscode asc) LOOP
 o_area := o_area || v_rec_record.name;
 
 END LOOP;
 return;
END;
$$
language plpgsql;

根据父级查询子级

with recursive cte as
(
select a.atid,cast(a.name as varchar(200)) from app_aqxj_equipment a 
where a.atid='036bc777-c718-4a81-bbc7-b8fe6f8ce913'
union all 
select k.atid,cast(c.name||'>'||k.name as varchar(200)) as name  from app_aqxj_equipment k 
inner join cte c on c.atid = k.parent_id
where  k.type_id <> 'xunjianxiang'
)select atid,name from cte
WITH RECURSIVE subject_tree AS (
    -- 基础查询,选择父级记录
    SELECT plan_subject_id, parent_id, template_content
    FROM train_plan_subject
    WHERE plan_subject_id = 'e7bfe6ce837e4ee58e5642ab232df906'
  UNION ALL
    -- 递归查询,查找当前结果的子级
    SELECT t.plan_subject_id, t.parent_id, t.template_content
    FROM train_plan_subject t
    INNER JOIN subject_tree st ON t.parent_id = st.plan_subject_id
)
SELECT * FROM subject_tree;

根据子级查询父级

WITH RECURSIVE dict AS (
     SELECT *
     FROM app_aqxj_equipment
     WHERE atid= '036bc777-c718-4a81-bbc7-b8fe6f8ce913'
     union ALL
     SELECT app_aqxj_equipment.*
     FROM app_aqxj_equipment,
          dict
     WHERE app_aqxj_equipment.atid = dict.parent_id
)
SELECT atid AS id, name as name, parent_id as parentId
FROM dict
ORDER BY name

从父级到子级

WITH RECURSIVE dict AS (
     SELECT *
     FROM app_aqxj_equipment
     WHERE atid= '036bc777-c718-4a81-bbc7-b8fe6f8ce913'
     union ALL
     SELECT app_aqxj_equipment.*
     FROM app_aqxj_equipment,
          dict
     WHERE app_aqxj_equipment.parent_id = dict.atid
)
SELECT atid AS id, name as name, parent_id as parentId
FROM dict
ORDER BY name

方法函数

SUBSTRING('abcd',2); -- result:bcd 表示从下标从2开始截取到末尾
SUBSTRING('abcd',1,2); -- result:ab 表示从下标从1开始,截取2个字符
to_char(date_trunc('day',now()),'yyyy-mm-dd') --时间格式转换为字符日期类型
to_date('2020-09-09','yyyy-mm-dd')) --把字符转换为日期格式 没有时分秒
to_timestamp('2020-09-09 22:22:00','yyyy-MM-dd hh24:mi:ss') --有时分秒
to_number(12,'99') --把字符转为数值型
split_part('2020-09-08','-',2) --分割字符,获取的是月,也就是09
concat_ws(':','1','2') --查询字段拼接 结果:1:2
string_agg(name,','); --多行合成一列,例如:张三,李四,王五,赵六
 
regexp_split_to_array('1,2,3',',') --返回数组格式
regexp_split_to_table('1,2,3',',') --拆分返回行模式
 
select case when 2>1 then '大于' else '小于' end --if判断
 
|| --字符拼接符
 
--其他类型格式转换
'1'::varchar
'1'::interger
'2020-01-01'::date
 
--当所有数据id全部一致时,没有唯一标识,使用下面这个函数可以查看隐藏的id
select ctid,* from wx_info limit 5
delete from wx_info where ctid in (select min(ctid) from wx_info where id = 1);
 
 
 
--查询行号
select 
row_number() over(order by recid) row_number
from jhrwbzs

创建游标

实用代码

实现夸库查询

--创建扩展
create extension
dblink;--dblink函数实现夸库查询
 
select * from dblink(
	'host=127.0.0.1 dbname=数据库名字 user=postgres password=postgres',
	'select atid,name from app_aqxj_place_info') as t
	(atid varchar(200),name varchar(200));

数学函数

函数返回类型描述例子结果
abs(x)绝对值abs(-17.4)17.4
cbrt(double)立方根cbrt(27.0)3
ceil(double/numeric)不小于参数的最小的整数ceil(-42.8)-42
degrees(double)把弧度转为角度degrees(0.5)28.6478897565412
exp(double/numeric)自然指数exp(1.0)2.71828182845905
floor(double/numeric)不大于参数的最大整数floor(-42.8)-43
ln(double/numeric)自然对数ln(2.0)0.693147180559945
log(double/numeric)10为底的对数log(100.0)2
log(b numeric,x numeric)numeric指定底数的对数log(2.0, 64.0)6.0000000000
mod(y, x)取余数mod(9,4)1
pi()double“π”常量pi()3.14159265358979
power(a double, b double)double求a的b次幂power(9.0, 3.0)729
power(a numeric, b numeric)numeric求a的b次幂power(9.0, 3.0)729
radians(double)double把角度转为弧度radians(45.0)0.785398163397448
random()double0.0到1.0之间的随机数值random()
round(double/numeric)圆整为最接近的整数round(42.4)42
round(v numeric, s int)numeric圆整为s位小数数字round(42.438,2)42.44
sign(double/numeric)参数的符号(-1,0,+1)sign(-8.4)-1
sqrt(double/numeric)平方根sqrt(2.0)1.4142135623731
trunc(double/numeric)截断(向零靠近)trunc(42.8)42
trunc(v numeric, s int)numeric截断为s小数位置的数字trunc(42.438,2)42.43

字符串函数和操作符

函数返回类型描述例子结果
string 丨丨 stringtext字串连接‘Post’ 丨丨 ‘greSQL’PostgreSQL
bit_length(string)int字串里二进制位的个数bit_length(‘jose’)32
char_length(string)int字串中的字符个数char_length(‘jose’)4
convert(string using conversion_name)text使用指定的转换名字改变编码。convert(‘PostgreSQL’ using iso_8859_1_to_utf8)‘PostgreSQL’
lower(string)text把字串转化为小写lower(‘TOM’)tom
octet_length(string)int字串中的字节数octet_length(‘jose’)4
overlay(string placing string from int [for int])text替换子字串overlay(‘Txxxxas’ placing ‘hom’ from 2 for 4)Thomas
position(substring in string)int指定的子字串的位置position(‘om’ in ‘Thomas’)3
substring(string [from int] [for int])text抽取子字串substring(‘Thomas’ from 2 for 3)hom
substring(string from pattern)text抽取匹配 POSIX 正则表达式的子字串substring(‘Thomas’ from ‘…$’)mas
substring(string from pattern for escape)text抽取匹配SQL正则表达式的子字串substring(‘Thomas’ from ‘%#”o_a#”_’ for ‘#’)oma
trim([leading丨trailing 丨 both] [characters] from string)text从字串string的开头/结尾/两边/ 删除只包含characters(默认是一个空白)的最长的字串trim(both ‘x’ from ‘xTomxx’)Tom
upper(string)text把字串转化为大写。upper(‘tom’)TOM
ascii(text)int参数第一个字符的ASCII码ascii(‘x’)120
btrim(string text [, characters text])text从string开头和结尾删除只包含在characters里(默认是空白)的字符的最长字串btrim(‘xyxtrimyyx’,’xy’)trim
chr(int)text给出ASCII码的字符chr(65)A
convert(string text, [src_encoding name,] dest_encoding name)text把字串转换为dest_encodingconvert( ‘text_in_utf8’, ‘UTF8’, ‘LATIN1’)以ISO 8859-1编码表示的text_in_utf8
initcap(text)text把每个单词的第一个子母转为大写,其它的保留小写。单词是一系列字母数字组成的字符,用非字母数字分隔。initcap(‘hi thomas’)Hi Thomas
length(string text)intstring中字符的数目length(‘jose’)4
lpad(string text, length int [, fill text])text通过填充字符fill(默认为空白),把string填充为长度length。 如果string已经比length长则将其截断(在右边)。lpad(‘hi’, 5, ‘xy’)xyxhi
ltrim(string text [, characters text])text从字串string的开头删除只包含characters(默认是一个空白)的最长的字串。ltrim(‘zzzytrim’,’xyz’)trim
md5(string text)text计算给出string的MD5散列,以十六进制返回结果。md5(‘abc’)
repeat(string text, number int)text重复string number次。repeat(‘Pg’, 4)PgPgPgPg
replace(string text, from text, to text)text把字串string里出现地所有子字串from替换成子字串to。replace(‘abcdefabcdef’, ‘cd’, ‘XX’)abXXefabXXef
rpad(string text, length int [, fill text])text通过填充字符fill(默认为空白),把string填充为长度length。如果string已经比length长则将其截断。rpad(‘hi’, 5, ‘xy’)hixyx
rtrim(string text [, character text])text从字串string的结尾删除只包含character(默认是个空白)的最长的字rtrim(‘trimxxxx’,’x’)trim
split_part(string text, delimiter text, field int)text根据delimiter分隔string返回生成的第field个子字串(1 Base)。split_part(‘abc~@~def~@~ghi’, ‘~@~’, 2)def
strpos(string, substring)text声明的子字串的位置。strpos(‘high’,’ig’)2
substr(string, from [, count])text抽取子字串。substr(‘alphabet’, 3, 2)ph
to_ascii(text [, encoding])text把text从其它编码转换为ASCII。to_ascii(‘Karel’)Karel
to_hex(number int/bigint)text把number转换成其对应地十六进制表现形式。to_hex(9223372036854775807)7fffffffffffffff
translate(string text, from text, to text)text把在string中包含的任何匹配from中的字符的字符转化为对应的在to中的字符。translate(‘12345′, ’14’, ‘ax’)a23x5

类型转换相关函数

函数返回类型描述实例
to_char(timestamp, text)text将时间戳转换为字符串to_char(current_timestamp, ‘HH12:MI:SS’)
to_char(interval, text)text将时间间隔转换为字符串to_char(interval ’15h 2m 12s’, ‘HH24:MI:SS’)
to_char(int, text)text整型转换为字符串to_char(125, ‘999’)
to_char(double precision, text)text双精度转换为字符串to_char(125.8::real, ‘999D9’)
to_char(numeric, text)text数字转换为字符串to_char(-125.8, ‘999D99S’)
to_date(text, text)date字符串转换为日期to_date(’05 Dec 2000′, ‘DD Mon YYYY’)
to_number(text, text)numeric转换字符串为数字to_number(‘12,454.8-‘, ’99G999D9S’)
to_timestamp(text, text)timestamp转换为指定的时间格式 time zone convert string to time stampto_timestamp(’05 Dec 2000′, ‘DD Mon YYYY’)
to_timestamp(double precision)timestamp把UNIX纪元转换成时间戳

三角函数列表

函数描述
acos(x)反余弦
asin(x)反正弦
atan(x)反正切
atan2(x, y)正切 y/x 的反函数
cos(x)余弦
cot(x)余切
sin(x)正弦
tan(x)正切

函数详细:https://www.runoob.com/postgresql/postgresql-functions.html

这是 父级查询所有子级的!!!

with recursive cte as
(
select a.atid,cast(a.name as varchar(200)) from app_aqxj_equipment a
where a.atid=239972297dd742e28043bfdfa9eef264′
union all
select k.atid,cast(c.name||>||k.name as varchar(200)) as name from app_aqxj_equipment k
inner join cte c on c.atid = k.parent_id
where k.type_id <> ‘xunjianxiang’
)select atid,name from cte
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张童瑶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值