错误 - 使用CTE进行递归选择时,"UNION运算符必须具有相同数量的表达式"

 手机用户2502917141 发布于 2023-02-13 17:42

这时我有一张tblLocation带有柱子的桌子ID, Location, PartOfID.

该表以递归方式连接到自身: PartOfID -> ID

我的目标是选择输出如下:

> France > Paris > AnyCity >

说明:AnyCity位于巴黎,巴黎位于法国.

我到现在为止找到的解决方案是这样的:

; with q as (
select ID,Location,PartOf_LOC_id from tblLocatie t
where t.ID = 1 -- 1 represents an example
union all
select t.Location + '>' from tblLocation t
inner join q parent on parent.ID = t.LOC_PartOf_ID
)
select * from q

不幸的是我收到以下错误:

使用UNION,INTERSECT或EXCEPT运算符组合的所有查询在其目标列表中必须具有相同数量的表达式.

如果您知道如何修复我的输出,那就太棒了.

1 个回答
  • 问题在于:

    --This result set has 3 columns
    select LOC_id,LOC_locatie,LOC_deelVan_LOC_id from tblLocatie t
    where t.LOC_id = 1 -- 1 represents an example
    
    union all
    
    --This result set has 1 columns   
    select t.LOC_locatie + '>' from tblLocatie t
    inner join q parent on parent.LOC_id = t.LOC_deelVan_LOC_id
    

    为了使用unionunion all数量的列和它们的类型应该是相同的跨所有结果集.

    我想你应该只将列添加LOC_deelVan_LOC_id到第二个结果集中

    2023-02-13 17:46 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有