2010-06-20 19 views
1

我想查询两个表如下,以获取新表中没有在当前表中的名称或代码条目的行。sql查询来获取跨表的新数据

table current 

name   code 
japan   233 
india   65 
england  44 


table new 

name   code 
japan   233 
india   65 
england-main 44 
japan   2331 
india   652 
usa   1 

在这种exampe它应该返回

name   code 
usa   1 

哪些SQL查询将归档此enter code here

回答

1
SELECT name, code 
FROM new n 
WHERE NOT EXISTS(SELECT * FROM current c 
       WHERE c.name = n.name OR c.code = n.code) 
+0

这在sqlite中有效。谢谢 – veccy 2010-06-20 16:01:33

1
SELECT name, code 
FROM new 
WHERE name NOT IN (SELECT DISTINCT name FROM current) 
AND code NOT IN (SELECT DISTINCT code FROM current); 

不知道你正在使用什么味道的SQL的,所以这个查询可能不同或根本不工作。

后编辑:此查询将检查名称和代码是否存在于当前表中。但是,它不检查它们是否在同一条记录中。

+0

我在sqlite的测试。我将在访问中实现。然而,这代码返回 英格兰适当美国 它不应该挑“英格兰正确44”,因为44是已经存在于当前 – veccy 2010-06-20 15:46:28

+0

哦,你正在检查的代码值以及代码值?等一下,会编辑。 – 2010-06-20 15:48:54

0
select * from 
(select 
    n.*, 
    c.code as old_code 
from 
    new as n left join 
    current as c on n.code = c.code) as T 
where T.old_code is null 

或者干脆

select * from new as n where not exist (select 1 from current as c where c.code = n.code) 
0
select * from new where name not in (select name from current) and code not in (select code from current); 

会做的伎俩在MySQL

+0

我正在试图 – veccy 2010-06-20 15:57:02

0

试试这个:

select * from new_table where name not in (select name from current_table) and 
code not in (select code from current_table); 
+0

它需要检查名称和代码 – veccy 2010-06-20 15:56:32

+0

@veccy:如果您还想要代码,我已更新。 – Sarfraz 2010-06-20 15:58:31

+0

这在sqlite中也起作用 – veccy 2010-06-20 16:05:42