2013-03-31 66 views
-1

那麼有沒有一種方法,使這樣的:MySQL的左連接和失蹤行

表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 

有沒有辦法做到這一點?

+0

你試圖執行什麼業務規則?您是否正在尋找一種方法來保證結果至少包含一行第二列爲NULL值的行? – BellevueBob

回答

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 
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)。

+0

內部連接/工會所有版本應該比左連接/工會執行稍好一點 – aguyngueran

+0

有沒有辦法做到這一點沒有工會? –

+0

@AlineGolvalve我不明白如何避免'UNION';你需要爲第一個條件包含一個額外的行。 aguyngueran是正確的;一個'INNER JOIN'和'UNION ALL'可能會表現更好,並給出相同的結果。 – BellevueBob