POSTGRESQL中ERROR: recursive query "t" column 2 has type character varying(150) in non-recursive term but type character varying overall

时间:2021-09-06 16:28:59

最近在做项目的时候有个需求是需要查到当前登录的用户下辖所有区域的数据,并将查询出来的部门信息以如下格式展示

最高人民法院>江苏省高级人民法院>南通市中级人民法院
最高人民法院>江苏省高级人民法院>连云港市中级人民法院

,于是用如下语句查询

WITH RECURSIVE T AS (
SELECT
c_id,
c_name
FROM
db_aty.t_aty_corp
WHERE
c_pid IS NULL
UNION ALL
SELECT
D.c_id,
T.c_name || '>' || D.c_name
FROM
db_aty.t_aty_corp D
JOIN T ON D.c_pid = T .c_id
) SELECT
c_id AS corpId,
c_name AS corpName
FROM
T

但是出现了如下错误

ERROR:  recursive query "t" column 2 has type character varying(150) in non-recursive term but type character varying overall

根据错误提示猜测这是因为在sql语句中使用union all 时  需要前后查询出的字段属性一致,而在进行查询时,使用t.c_name || '>' || D.c_name 时由于是拼接的字符串 所以字段属性与前面的

c_name不一致,所以导致报错,

解决办法:为拼接后的字符串指定字段格式

WITH RECURSIVE T  AS (
SELECT
c_id,
c_name::varchar(150) FROM
db_aty.t_aty_corp
WHERE
c_pid is null
UNION ALL
SELECT
D.c_id,
(T.c_name || '>' || D.c_name )::varchar(150) as c_name
FROM
db_aty.t_aty_corp D
JOIN T ON D.c_pid = T .c_id
)
SELECT c_id AS corpId ,c_name as corpName FROM T

得到正确答案如下

POSTGRESQL中ERROR:  recursive query "t" column 2 has type character varying(150) in non-recursive term but type character varying overall