2017-01-30 194 views
0

我想要一個左外連接與n:m連接表之間。SQL左外連接與n:m連接表

Table A 
    column: id_a 

Table A:B 
    column: id_a 
    column: id_b 

Table B 
    column: id_b 

表b保存所有可能的行。所以B列必須在左邊。

我無法弄清楚如何呈現,以示對1個表A.我想告訴所有entires的misssing那些所有可能的值和(即爲什麼左外)

使用MySQL

的樣本數據。

筐(表A)

1 | basket x 
2 | basket y 

果(表B)

1 | apple 
2 | strawberries 
3 | grapes 
4 | lemon 

連接表

1 | 1 
1 | 2 
2 | 1 
2 | 2 
2 | 3 

結果 結果爲籃X查詢

1 | 1 
1 | 2 
1 | 3 (something which indicates it is not assigned . since there is no connection) 
1 | 4 (something which indicates it is not assigned . since there is no connection) 
+0

您正在使用什麼版本的SQL的? –

+2

你能告訴我們樣品數據和你的預期產量嗎? –

+1

請** [編輯] **您的問題,並根據該數據添加一些示例數據和預期輸出。 [**格式化文本**](http://stackoverflow.com/help/formatting)請,[無屏幕截圖](http://meta.stackoverflow.com/questions/285551/why-may-i-not上傳問題時的代碼問題/ 285557#285557) –

回答

0

我認爲你需要一個cartesian結果。考慮下面的示例,

declare @baskets table(basket_id int not null primary key identity, basketName varchar(255)); 
declare @fruits table(fruit_id int not null primary key identity, fruitName varchar(255)); 
declare @basketsFruits table(basket_id int not null, fruit_id int not null); 

insert into @baskets(basketName) 
    values('basket x'), ('basket y'); 

insert into @fruits(fruitName) 
    values('apple'), ('strawberries'), ('grapes'), ('lemon'); 

insert into @basketsFruits(basket_id, fruit_id) 
    values(1, 1), (1, 2), (2, 1), (2, 2), (2, 3); 


select b.*, f.fruitName 
     , case when exists(select 1 from @basketsFruits as bf where bf.basket_id = b.basket_id and bf.fruit_id = f.fruit_id) then 
      'Fruit Present' 
     else 
      'Fruit not Present' 
     end as fruitStatus 
from @baskets as b, @fruits as f  -- cartesian all the fruits and all the baskets 
where b.basket_id = 1 

結果:

query results

+0

謝謝sallushan !!! –