复杂SQL语句提问

来源:百度知道 编辑:UC知道 时间:2024/06/25 20:10:42
TABLE t1 和 TABLE t2 表结构相同,但数据不同:

t1:
create table t1(
id int,
tm datetime,
data varchar(200)
)
数据:

1 2009-11-11 数据1
1 2009-11-12 数据2
2 2009-11-12 数据3
3 2009-11-12 数据4

t2:
create table t2(
id int,
data varchar(200)
)
数据:

1 2009-11-11 数据1
1 2009-11-12 数据2
2 2009-11-12 数据3
2 2009-11-13 数据3
2 2009-11-14 数据3
3 2009-11-12 数据4

现在我想用它一条语句将 t2 中有,而 t1 没有的数据查出来,HOW?
效率高一点的。另外,1楼和2楼的语句,在SELECT中不能添加 WHERE 吗?
我的T1和T2都有50W条,很大的
数据库为 MS SQL 2000

t2:
create table t2(
id int,
tm datetime,
data varchar(200)
)

CREATE UNIQUE INDEX asdfadsf ON t1(id,tm);
CREATE UNIQUE INDEX asdfadsf2 ON t2(id,tm);

查询条件中一定要加一个: TM > '2009-11-09'

select * from t2 where convert(varchar(10),t2.id)+convert(varchar(25),t2.tm,120)+convert(varchar(200),t2.data) not in(
select convert(varchar(10),t2.id)+convert(varchar(25),t2.tm,120)+convert(varchar(200),t2.data) from t2,t1 where t2.id=t1.id and t2.tm=t1.tm and t2.data=t1.data
)

兄弟你这个难度有点大阿 效率高不了

select t2.* from t2
where t2.TM > '2009-11-09' and not exists(select 1 from t1 where t1.data=t2.data)

数据量大的时候就用exists,这样会大大的提高SQL性能。

崩溃,下面竟然有人说not in效率比not exists高

建议这位仁兄随便找一张数据量大的表,做一下SQL成本分析。

100万条记录,用not exists要比not in快10多倍。

如果你的sql2000数据库,楼上兄弟们答的你可能用不了。试试这个:

select * from t2 where cast(id as varchar(10))+','+data not in (select cast(id as varchar(10))+','+data from t1)

select id,data from t2
except
select id,data from t1

select * from(select * from t2 where t2.id not in (select id from t1 where t1.id =not null)) as T 我看了你的表,最好用ID来判断