2013-05-15 46 views
0

数据:使用上选择语句的ID的下选择语句的WHERE子句中在一台Union

表1:

ID   Value1   Date1 
1   foo    2013-04-27 
2   bar    2013-05-01 
3   umm    2013-05-29 
4   ba    2013-06-09 
5   sne    2013-04-30 
6   xyz    2013-07-11 
7   aosid   2013-07-08 

LinkTable:

link  MainID   SubID 
A   1    3 
B   3    1 
A   1    4 
B   4    1 
A   2    6 
B   6    2 

查询:

select t1.ID, t1.Value1, t1.Date1 
from Table1 t1 
where t1.Date1 between '2013-04-24' and '2013-05-08' 

union 

select t2.ID, t2.Value1, t2.Date1 
from Table1 t2 
where t2.ID in (select LT.SubID 
       from LinkTable LT 
       where LT.link = 'A' and LT.MainID = t1.ID) 

所以这是wha t我刚刚尝试过,并且出现t1.ID无法绑定的错误。这意味着我不能使用第二个选择中的数据。

有没有一种方法可以使用第二个select中的第一个select的ID值?

感谢您的帮助。

期望的结果:

ID  Value1  Date1 
1  foo   2013-04-27 
3  umm   2013-05-29 
4  ba   2013-06-09 
2  bar   2013-05-01 
6  xyz   2013-07-11 
5  sne   2013-04-30 

所以要解释结果好一点的第一选择应该包括在该日期范围内的所有记录,现在是第二选择会看,看它是否被链接到一个通过LinkTable从第一个选择中包含的记录中。

+0

@AzizShaikh我加了预期的效果。谢谢 –

回答

2

我想你想的CTE,以帮助你的逻辑修改您的查询。

根据您的澄清,我想出了这个办法没有工会:

with ids as (
     select t1.* 
     from table1 t1 
     where t1.Date1 between '2013-04-24' and '2013-05-08' 
    ) 
select t1.* 
from table1 t1 left outer join 
    linktable lt 
    on t1.id = lt.subid and 
     lt.mainid in (select id from ids) 
where lt.mainid is not null or 
     t1.Date1 between '2013-04-24' and '2013-05-08' 

,您也可以改写为联合:

with ids as (
     select t1.* 
     from table1 t1 
     where t1.Date1 between '2013-04-24' and '2013-05-08' 
    ) 
select t.* 
from ((select * from ids) 
     union 
     (select * 
     from table1 t1 join 
      linktable lt 
      on t1.id = lt.subid 
     where lt.mainid in (select id from ids) 
    ) 
    ) t 
+0

由于日期范围,结果为5,但由于7不在日期范围内,也不在链接表中。基本上我想要在日期范围内的记录,或者如果它们不在日期范围内,它们是链接到LinkTable中的另一个ID的。 –

+0

非常感谢,我用你的第一个例子,它完美的作品:) –

0

不,联合子查询是相互独立的。 您可以快速与这一个(我没有想过最好的一个,只是修改了的)

select t1.ID, t1.Value1, t1.Date1 
from Table1 t1 
where t1.Date1 between '2013-04-24' and '2013-05-08' 

union 

select t2.ID, t2.Value1, t2.Date1 
from Table1 t2 
where t2.ID in (select LT.SubID 
      from LinkTable LT 
      left join Table1 t1 on LT.MainID = t1.ID 
      where LT.link = 'A' and t1.Date1 between '2013-04-24' and '2013-05-08')