-1

那么有没有办法制作类似的东西:

表格1

id -> PK
table1_id -> FK

id | name | table1_id
1,'test',NULL
2,'test2',NULL
3,'sub_val1',1
4,'sub_val2',1

select a.name
     , b.name 
from table1 a 
left join table1 b 
   on a.id=b.table1_id 
where a.table1_id is null;

这将返回如下内容:

test,sub_val1
test,sub_val2
test2,NULL

我希望它返回如下内容:

test,NULL
test,sub_val1
test,sub_val2
test2,NULL

有办法吗?

4

2 回答 2

0

我唯一想到的是:

select
    a.name,
    b.name
from
    table1 a
inner join
    table1 b on a.id = b.table1_id
where
    a.table1_id is null
union all
    select name, null from table1 where table1_id is null
于 2013-03-31T19:09:16.517 回答
0

我只是在猜测,但也许这就是你想要的:

select a.name as first_name
     , b.name as second_name
from table1 a 
left join table1 b 
   on a.id=b.table1_id 
where a.table1_id is null
union
select name as first_name
     , null as second_name
from table1  
where table1_id is null
order by first_name, second_name

您可能需要在第二个操作 (UNION) 中指定第二列的定义。

于 2013-03-31T19:09:38.477 回答