2015-09-04 93 views
1

我一直在試圖開發一個查詢來解決問題,但它很難。從表2返回來自表1上不同ID的相同名稱

表1:

+------+----+ 
| NAME | ID | 
+------+----+ 
| A | 1 | 
| A | 2 | 
| B | 1 | 
| B | 5 | 
| C | 8 | 
+------+----+ 

表2:

+------+----+ 
| NAME | ID | 
+------+----+ 
| A | 1 | 
| A | 4 | 
| B | 3 | 
| B | 5 | 
| D | 9 | 
+------+----+ 

從這些結果,我需要從表2的名稱表1中包含與ID不返回的一切。

所以,這個例子中,回報應該是:

+------+----+ 
| NAME | ID | 
+------+----+ 
| A | 4 | 
| B | 3 | 
+------+----+ 

回答

1

你可能想試試這個:

編輯:用WITH子句中的簡單子查詢替換table1和table2。

WITH table1 AS 
(
SELECT 
    DECODE(LEVEL,1, 'A',2, 'A',3, 'B',4, 'B',5, 'C') AS name 
    ,DECODE(LEVEL,1, 1,2, 2,3, 1,4, 5,5, 8) AS id 
FROM 
    dual 
CONNECT BY LEVEL < 6 
) 
,table2 AS 
(
SELECT 
    DECODE(LEVEL,1, 'A',2, 'A',3, 'B',4, 'B',5, 'D') AS name 
    ,DECODE(LEVEL,1, 1,2, 4,3, 3,4, 5,5, 9) AS id 
FROM 
    dual 
CONNECT BY LEVEL < 6 
) 
SELECT 
    t2.id 
    ,t2.name 
FROM 
    table1 t1 
    ,table2 t2 
WHERE 
    t1.name = t2.name -- here we take all the records from table2, which have the same names as in table1 
MINUS -- then we "subtract" the records that have both the same name and id in both tables 
SELECT 
    t2.id 
    ,t2.name 
FROM 
    table1 t1 
    ,table2 t2 
WHERE 
    t1.name = t2.name 
    AND t1.id = t2.id 
+0

沒有回報..會試圖發現問題出在哪裏 –

+0

嘿。用一些示例table1和table2更新了我的查詢。 – AndrewMcCoist

+0

@AndrewMcCoist FWIW,您的查詢對我來說工作得很好,至少當我將它與我用於我的答案的相同數據集進行對比時。我不完全確定爲什麼OP似乎遇到了問題,似乎是按照他們的要求做了答案! – Boneist

0

您可以使用NOT EXISTS或類似:

SELECT t2.* 
FROM Table2 t2 
WHERE NOT EXISTS 
(
    SELECT 1 
    FROM Tabl1 t1 
    WHERE t1.Name = t2.Name 
    AND t1.Id = t2.Id 
); 
0
SELECT T1.ID,T1.NAME 
FROM TABLE2 T1 INNER JOIN TABLE1 T2 ON T1.NAME = T2.NAME 
       LEFT JOIN TABLE1 T3 ON T3.ID = T1.ID 
WHERE T3.ID IS NULL 
1

我會做:

with t1 as (select 'A' name, 1 id from dual union all 
      select 'A' name, 2 id from dual union all 
      select 'B' name, 1 id from dual union all 
      select 'B' name, 5 id from dual union all 
      select 'C' name, 8 id from dual), 
    t2 as (select 'A' name, 1 id from dual union all 
      select 'A' name, 4 id from dual union all 
      select 'B' name, 3 id from dual union all 
      select 'B' name, 5 id from dual union all 
      select 'D' name, 9 id from dual) 
select name, id 
from t2 
where name in (select name from t1) 
minus 
select name, id 
from t1; 

NAME   ID 
---- ---------- 
A    4 
B    3 
+0

它返回t1沒有的名稱。而查詢應該只顯示T2所具有的ID,而T1不具有相同的名稱。就像這個例子。 –

+0

我的查詢以什麼方式返回t1沒有的名字?!如果是這樣的話,結果將包括(name,id)=('D',9),他們沒有。我的(姓名,身份證)=('A',4)和('B',3)的結果與您所期望的結果完全符合您的問題! – Boneist

+0

我prolly錯誤轉換爲正確的格式。它只是在這裏工作。 –

相關問題