2017-01-06 186 views
0

我遇到了形成sql查詢的問題。SQL:左連接查詢

表stucture:

TABLE A: 
id  | data_a 
--------|-------- 
1  | data1 
2  | data2 
3  | data3 

TABLE B: 
    id  | data_b | a_id 
--------|--------|-------- 
    1  | data4 | 1 
    2  | data5 | 1 
    3  | data6 | 2 
    4  | data7 | 3 
    5  | data8 | 3 

TABLE C: 
    id  | data_c | b_id | x_id 
--------|--------|--------|-------- 
    1  | data9 | 1  | 1 
    2  | data10 | 2  | 1 
    3  | data11 | 3  | 1 
    4  | data12 | 1  | 2 
    5  | data13 | 4  | 2 

需要的輸出:

data_a | data_b | data_c 
--------|--------|-------- 
data1 | data4 | data12 
data1 | data5 | 
data2 | data6 | 
data3 | data7 | data13 
data3 | data8 | 

當前的SQL:

SELECT data_a, data_b, data_c 
FROM a 
LEFT JOIN b ON a.id = b.a_id 
LEFT JOIN c ON b.id = c.b_id 
WHERE c.x_id = 2 OR c.x_id = null; 

SQL fiddle

+0

請添加一些解釋,你要做什麼。 – shmosel

+0

@shmosel試圖獲得所需的輸出 – meeeee

+0

我一般用sql小提琴來提升qustions,並且在表a,表b,表c下降問題。你爲什麼不想讓事情變得困難? – e4c5

回答

5

把X_ID = 2左連接條件。

SELECT 
    data_a, 
    data_b, 
    data_c 

FROM 
    a LEFT JOIN b ON a.id = b.a_id 
    LEFT JOIN c ON b.id = c.b_id and c.x_id=2; 
1

試試這個: -

SELECT 
    data_a, 
    data_b, 
    data_c 

FROM 
    (Select data_a,data_b,b.id from a LEFT JOIN b ON a.id = b.a_id) as k 
    LEFT JOIN (Select * from c WHERE 
    c.x_id = 2 OR c.x_id = null) as j ON k.id = j.b_id 

完全匹配只是補充一點: -

order by data_a,data_b 
+0

感謝您的幫助。這確實有用,但wonderbell的答案不需要嵌套的select語句 – meeeee