表a表aHistory在外键关系,他们都有一个字段叫做IsDraft,现在要搜索两个表中符合条件的记录,并且两个表中的IsDraft=0.其中如果表a中IsDraft=1,那它对应表aHistory中的记录也要找出来.以下sql语句有问题,因为a.IsDraft=0没有记录,它都是IsDraft=1的,但是忽略IsDraft条件之后left outer join表aHistory之后有记录,我希望把aHistory中的记录找出来.怎么改select * from a left outer join ahistory on a.id = ahistory.aid
where a.IsDraft = 0 and ..
where a.IsDraft = 0 and ..
left outer join aHistory b on a.[id]=b.[fk_id]
--现在要搜索两个表中符合条件的记录,并且两个表中的IsDraft=0.其中如果表a中IsDraft=1,那它对应表aHistory中的记录也要找出来
--表述不清。猜你的意思是
--1.有自定义条件(例1=1).满足自定义条件且同时a.IsDraft=b.IsDraft=0,记录有效
--2.如果a.IsDraft=1,则不管其它条件。记录有效
where (a.IsDraft=0 and b.IsDraft=0 and 1=1)
or (a.IsDraft=1)
=======
如果按这个讲法,那什么条件都不用加.
刚刚看了看你的问题,实在是看不懂...
有点不懂你的意思哦,当两个表中的IsDraft=0都成立的时候,或者 表a中的IsDraft=1的时候把aHistory的信息捞出来吗, 是这样的代码如下:
select a.*,ahistory.* from a left join ahistory on a.id = ahistory.aid
where (a.IsDraft = 0) or(a.IsDraft=1)
我觉得这样就可以了吧 我机子试不了 你自己看看,你说的业有点不清楚吧
set nocount on
create table a(id varchar(20),f1 varchar(20),isdraft int)
insert into a select '1','bb1',0
insert into a select '2','dd1',1create table ahistory(aid varchar(20),f1 varchar(20),isdraft int)
insert into ahistory select '1','bb2',1
insert into ahistory select '2','dd2',1go
--测试
select a.id,case when a.isdraft=1 then a.f1 else ahistory.f1 end as f1
from a left outer join ahistory on a.id = ahistory.aid
--删除测试环境
drop table ahistory
drop table a
set nocount off
set nocount on
create table a(id varchar(20),f1 varchar(20),isdraft int)
insert into a select '1','bb1',0
insert into a select '2','dd1',1create table ahistory(aid varchar(20),f1 varchar(20),isdraft int)
insert into ahistory select '1','bb2',1
insert into ahistory select '2','dd2',1go
--测试
select a.id,case when a.isdraft=1 then a.f1 else ahistory.f1 end as f1
from a left outer join ahistory on a.id = ahistory.aid
--删除测试环境
drop table ahistory
drop table a
set nocount off就是取出两个表中的所有记录,然后除去isDraft=1的,就是上面结果应该是三条记录,仅仅除掉第一条'1','bb1',0
。MS很简单,由于其它相关条件的干扰,开始想多了。我知道怎么做了。
谢谢各位。