如何从两个表中获取未映射的行

时间:2013-04-15 04:31:31

标签: mysql sql sql-server

我在SQL查询中面临问题

我有两张桌子:

表一

ID Number
1  100
2  200
3  300
4  400
5  500
6  600
7  700
8  800
9  900

表二

ID Someotherdata
1  100
2  200
3  300
4  400
5  500

我尝试过查询

Select one.ID,one.Number
from table1 one
Left Outer Join
table2 two
on one.ID=two.id

我想要结果

6  600
7  700
8  800
9  900

3 个答案:

答案 0 :(得分:1)

使用except

Select one.ID,one.Number
from table1 one
except
(Select one.ID,one.Number
from table1 one
inner join
table2 two
on one.ID=two.id)

<强> SQL Fiidle to test

编辑(在OP请求中)

SELECT table1.id, table1.number FROM table1
LEFT JOIN table2 on table2.id = table1.id
WHERE table2.id  IS NULL

<强> Here is the SQL Fiidle for Testing

答案 1 :(得分:0)

从我看到的,你有两个具有相应ID的表。并非table1中的所有条目都在table2中,但table2中显示的条目与table1的ID相同。

这应该有效:

SELECT table1.id, table1.number FROM table1
LEFT JOIN table2 on table1.id = table2.id
WHERE table2.id IS NOT NULL

答案 2 :(得分:0)

Select one.ID,one.Number
from table1 one
Where not in(Select two.ID From Table2 two)