我有以下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
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
:WHEN d.level = 3 THEN 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
如何投射输出并修复它?
答案 0 :(得分:2)
case
表达式返回单个类型,派生自then
和where
子句中的类型。默认情况下,NULL
是文字(我认为)。
您的案例似乎是混合类型。所以,转换价值观。 Postgres有一个很好的简写::<type>
:
(CASE WHEN d.level = 2 THEN d.uid::text
ELSE dtr.subtype::text
END) AS subtype,
您希望在CASE
内进行转换,否则您可能会遇到运行时错误,因为尝试将字符串转换为数字。