2014-01-27 54 views
1

我只需要從三個表中獲取唯一的行。我如何做到這一點?如何從連接中刪除重複的行(SQL)

我有一個SQL查詢:

SELECT * 
FROM l_req 
LEFT JOIN p_req ON (p_req.uid = l_req.uid) 
LEFT JOIN r_req ON (r_req.uid = l_req.uid) 
WHERE l_req.uid = 100931362 

表架構:

Table l_req 

id column2 column3 uid 

1  2  3  100931362 
2  3  4  100931362 
3  4  5  100931362 

Table p_req 

id column2 column3 uid 

1  6  5  100931362 

查詢結果:

id column2 column3 uid    id1 column21 column31 uid1 
1  2  3  100931362  1  6  5  100931362 
2  3  4  100931362  1  6  5  100931362 
3  4  5  100931362  1  6  5  100931362 

=>我具有由重複的行一個JOIN。

我需要的結果是這樣的:

id column2 column3 uid    id1 column21 column31 uid1 
1  2  3  100931362  1  6  5  100931362 
2  3  4  100931362  NULL NULL NULL NULL 
3  4  5  100931362  NULL NULL NULL NULL 
+0

你不能用左連接做到這一點。如果您的條件匹配多次,他們也會加入多次。你能解釋爲什麼你需要爲以後的結果空值?如果出於性能方面的原因,也許你應該考慮從多個表中選擇而不是聯合,聯合查詢甚至是臨時表,以便更好地適應。 –

+0

你能解釋你想做什麼?也許有人可以用另一種解決方案提供有用的答案。 – ranisalt

+0

@scrowler,我只需要唯一的值,所以我想獲得一個NULL值。我希望你能用有效的查詢來幫助我。 向問題添加了更多信息。 – owl

回答

1

因爲你的表結構外觀幾乎一樣,還有其他選項供您不僅僅是連接。這裏有一個可能的解決方案:使用unions

設置一個手動字段名​​稱,用於標識行來自哪個表,以便在聯合後可以區分,因爲結果在其他情況下看起來都是相同的。

SELECT 'l_req' AS table_name, id, column2, column3, uid FROM l_req WHERE uid = 100931362 
UNION ALL 
SELECT 'p_req' AS table_name, id, column2, column3, uid FROM p_req WHERE uid = 100931362 
UNION ALL 
SELECT 'r_req' AS table_name, id, column2, column3, uid FROM r_req WHERE uid = 100931362 

我也在這裏假設你的r_req表具有相同的結構等。你可以期望從這個查詢的結果可能是這樣認爲:

table_name id column2 column3 uid 
l_req  1 2 3 100931362 
l_req  2 3 4 100931362 
l_req  3 4 5 100931362 
p_req  1 6 5 100931362 -- this is your extra result original from join 
+0

謝謝,但不是更有效率的加入? – owl

+0

@owl你試過我的解決方案嗎? –

0

你可以嘗試這樣的

Select id,column2,column3,Uid from 
(
SELECT * 
FROM l_req,ROW_NUMBER() OVER(PARTITION BY id,column2,column3 ORDER BY id ASC) AS RN 
LEFT JOIN p_req ON (p_req.uid = l_req.uid) 
LEFT JOIN r_req ON (r_req.uid = l_req.uid) 
WHERE l_req.uid = 100931362 
) AS T 

Where RN = 1 

(OR)

Select Case when RN = 1 Then id Else Null End, 
     Case when RN = 1 Then column2 Else Null End, 
     Case when RN = 1 Then column3 Else Null End, 
     Case when RN = 1 Then uid Else Null End 
(
SELECT * 
FROM l_req,ROW_NUMBER() OVER(PARTITION BY id,column2,column3 ORDER BY id ASC) AS RN 
LEFT JOIN p_req ON (p_req.uid = l_req.uid) 
LEFT JOIN r_req ON (r_req.uid = l_req.uid) 
WHERE l_req.uid = 100931362 
) AS T 

希望這有助於你