PostgreSQL将非递归项的输出强制转换为正确的类型
我有以下PostgreSQL查询:PostgreSQL将非递归项的输出强制转换为正确的类型,postgresql,Postgresql,我有以下PostgreSQL查询: WITH RECURSIVE disease_tree AS ( SELECT ref_disease_id, uid, parent, level, NULL AS subtype, NULL AS specific_subtype FROM ref_disease WHERE parent IS NULL UNION ALL SELECT d.ref_disease_id, d.uid, d.parent, d.level, CASE
WITH RECURSIVE disease_tree AS
(
SELECT ref_disease_id, uid, parent, level, NULL AS subtype, NULL AS specific_subtype
FROM ref_disease
WHERE parent IS NULL
UNION ALL
SELECT d.ref_disease_id, d.uid, d.parent, d.level,
CASE
WHEN d.level = 2 THEN d.uid
ELSE dtr.subtype END AS subtype,
CASE
WHEN d.level = 3 THEN d.name
ELSE NULL END AS specific_subtype
FROM ref_disease As d
INNER JOIN disease_tree AS dtr
ON d.parent = dtr.uid
)
select ref_disease_id, uid, level, subtype, specific_subtype from disease_tree
到目前为止一切正常。但是根据我的应用程序逻辑,我必须在下一行返回d.uid
而不是d.name
:当d.level=3时,则返回d.name
因此,新查询如下所示:
WITH RECURSIVE disease_tree AS
(
SELECT ref_disease_id, uid, parent, level, NULL AS subtype, NULL AS specific_subtype
FROM ref_disease
WHERE parent IS NULL
UNION ALL
SELECT d.ref_disease_id, d.uid, d.parent, d.level,
CASE
WHEN d.level = 2 THEN d.uid
ELSE dtr.subtype END AS subtype,
CASE
WHEN d.level = 3 THEN d.uid
ELSE NULL END AS specific_subtype
FROM ref_disease As d
INNER JOIN disease_tree AS dtr
ON d.parent = dtr.uid
)
select ref_disease_id, uid, level, subtype, specific_subtype from disease_tree
但它失败了,出现以下错误:
ERROR: recursive query "disease_tree" column 6 has type text in non-recursive term but type character varying overall
LINE 3: ..._disease_id, uid, parent, level, NULL AS subtype, NULL AS sp...
^
HINT: Cast the output of the non-recursive term to the correct type.
********** Error **********
ERROR: recursive query "disease_tree" column 6 has type text in non-recursive term but type character varying overall
SQL state: 42804
Hint: Cast the output of the non-recursive term to the correct type.
Character: 107
如何强制转换输出并修复它?一个
case
表达式返回一个类型,该类型派生自然后和where
子句中的类型。默认情况下,NULL
是文本(我认为)
您的案例似乎是混合类型。所以,转换这些值。Postgres有一个很好的缩写:
:
您希望在案例中执行转换,否则,当字符串试图转换为数字时,可能会出现运行时错误。强制转换空值:null::character variable
@a_horse_with_no_name。这不会先尝试将字符串值转换为数字吗?这可能会导致错误。错误的原因是非递归部分中的null
值的类型不正确
(CASE WHEN d.level = 2 THEN d.uid::text
ELSE dtr.subtype::text
END) AS subtype,