首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PostgreSQL将非递归项的输出转换为正确的类型

PostgreSQL将非递归项的输出转换为正确的类型
EN

Stack Overflow用户
提问于 2016-12-20 20:53:53
回答 1查看 3.7K关注 0票数 1

我有一个下面的PostgreSQL查询:

代码语言:javascript
复制
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.nameWHEN d.level = 3 THEN d.name

因此,新的查询如下所示:

代码语言:javascript
复制
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 

但它失败了,并显示以下错误:

代码语言:javascript
复制
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

如何转换输出并修复它?

EN

回答 1

Stack Overflow用户

发布于 2016-12-20 20:58:08

case表达式返回单个类型,该类型派生自thenwhere子句中的类型。默认情况下,NULL是文本(我认为)。

您的案例看起来像是混合类型。因此,转换这些值。Postgres具有::<type>的简写形式。

代码语言:javascript
复制
(CASE WHEN d.level = 2 THEN d.uid::text
      ELSE dtr.subtype::text
 END) AS subtype,

您希望在CASE中进行转换,否则在尝试将字符串转换为数字时可能会出现运行时错误。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41242858

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档