日期:2014-05-18  浏览次数:20577 次

关于写sql语句
有一个主从表:
主表#t1,数据如下:
id code
1 a1
2 a2
3 a3

从表#t2(#t2.id_t1与主表#t1.id关联),数据如下:
id id_t1 f1
1 1 t1
2 1 t2
3 3 t6


我想实现,如果#t1的数据没有对应从表#t2的数据时,就不要显示#t1的主表,
比如显示#t1主表:
id code
1 a1
3 a3

由于#t1.id=2时,找不到#t2的数据,所以不显示出来。如何写sql语句?




------解决方案--------------------
SQL code

--> 测试数据:[t1]
if object_id('[t1]') is not null drop table [t1]
create table [t1]([id] int,[code] varchar(2))
insert [t1]
select 1,'a1' union all
select 2,'a2' union all
select 3,'a3'
--> 测试数据:[t2]
if object_id('[t2]') is not null drop table [t2]
create table [t2]([id] int,[id_t1] int,[f1] varchar(2))
insert [t2]
select 1,1,'t1' union all
select 2,1,'t2' union all
select 3,3,'t6'
select distinct t2.id_t1,t1.code from t2 inner join t1 on t2.id_t1=t1.id

id_t1    code
1    a1
3    a3

------解决方案--------------------
select m.* from #t1 m where exists(select 1 from #t2 n where m.id = n.id_t1)
------解决方案--------------------
SQL code
create table [#t1]([id] int,[code] varchar(2))
insert [#t1]
select 1,'a1' union all
select 2,'a2' union all
select 3,'a3'
create table [#t2]([id] int,[id_t1] int,[f1] varchar(2))
insert [#t2]
select 1,1,'t1' union all
select 2,1,'t2' union all
select 3,3,'t6'

select m.* from #t1 m where exists(select 1 from #t2 n where m.id = n.id_t1)

drop table #t1 , #t2

/*
id          code 
----------- ---- 
1           a1
3           a3

(所影响的行数为 2 行)
*/