似乎问题是我无法使用当前方法,因为每个父级都有不同数量的子级,但我似乎无法找到另一种方法。有人有什么想法吗?
id Name parentId
1 Collecting -1
30 Other classic toys 19016
32 Dolls 1
34 Art 1
35 Paintings 34
38 Other Coca Cola 62848
57 Movie objects 196
63 Comic books 267
64 Other comics 900
使用UNION,INTERSECT或EXCEPT运算符组合的所有查询都必须 在目标列表中有相同数量的表达式。
我试过了:
with testtable as (
select *
from Categories c
where c.parentId = -1
union all
select *
from Categories cc
inner join testtable tt
on tt.id = rr.parentId
)
select * from testtable
列是'id','name'和'parentId'。
答案 0 :(得分:2)
而不是select *
,请写出列名select id, name, parentId
在回复您的评论时,您可以对父母以下的孩子进行排序,例如:
with testtable as (
select id, name, parentId, id as root
from Categories c
where c.parentId = -1
union all
select id, name, parentId, root
from Categories cc
inner join testtable tt
on tt.id = rr.parentId
)
select * from testtable order by root, parentId
这会将父级存储在root
列中。由于parentId
为-1
,父母将被排在孩子之上。
答案 1 :(得分:0)
两个选项中需要相同数量的列,例如:
表A:
create table TableA (
A varchar(255),
B varchar(255),
C varchar(255),
D varchar(255)
)
表B:
create table TableB (
A varchar(255),
B varchar(255),
C varchar(255)
)
你无法做到:
with unionselect do(
select * from TableA
union all
select * from TableB
)
因为表A有4列而表B只有3列
你可以改为使用" null"例如:
with unionselect do(
select a.A, a.B, a.C, a.D from TableA a
union all
select b.A, b.B, b.C, null from TableB b
)
所以在你的情况下,因为你正在加入" testtable"这可能会导致您的底部选择返回比第一个选择
更多的列最好的问候