从表2返回来自表1上不同ID的相同名称
我一直在试图开发一个查询来解决问题,但它很难。从表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 |
+------+----+
你可能想试试这个:
编辑:用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
您可以使用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
);
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
我会做:
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
它返回t1没有的名称。而查询应该只显示T2所具有的ID,而T1不具有相同的名称。就像这个例子。 –
我的查询以什么方式返回t1没有的名字?!如果是这样的话,结果将包括(name,id)=('D',9),他们没有。我的(姓名,身份证)=('A',4)和('B',3)的结果与您所期望的结果完全符合您的问题! – Boneist
我prolly错误转换为正确的格式。它只是在这里工作。 –
没有回报..会试图发现问题出在哪里 –
嘿。用一些示例table1和table2更新了我的查询。 – AndrewMcCoist
@AndrewMcCoist FWIW,您的查询对我来说工作得很好,至少当我将它与我用于我的答案的相同数据集进行对比时。我不完全确定为什么OP似乎遇到了问题,似乎是按照他们的要求做了答案! – Boneist