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

关于一个sql语句的写法
主表#t1数据如下:
SQL code

id    name
1      a
2      b
3      c



从表#t2(字段#t2.id_t1与#t1.id关联)数据如下:
SQL code

id    id_t1   f1
1       1     a1
2       1     a2
3       3     c1




我想写一个sql语句,根据字段#t2.id_t1与#t1.id关联,如果从表#t2没数据没有对应主表,则显示主表的数据来,比如#t1的数据如下:
SQL code

id    name
1      a
3      c


如何写这个sql语句?


------解决方案--------------------
SQL code
select * from #t1 a where not exists(select 1 from #t2 where id_t1=a.id)

------解决方案--------------------
探讨

SQL code
select * from #t1 a where not exists(select 1 from #t2 where id_t1=a.id)

------解决方案--------------------
探讨
SQL code

select * from #t1 a where not exists(select 1 from #t2 where id_t1=a.id)

------解决方案--------------------
探讨
引用:
SQL code

select * from #t1 a where not exists(select 1 from #t2 where id_t1=a.id)


把not去掉就可以了。
--或者:用嵌套子查询

SQL code

select * from t1 where id in(select id_t1 from t2)

------解决方案--------------------
探讨
根据字段#t2.id_t1与#t1.id关联,如果从表#t2没数据没有对应主表,则显示主表的数据来