在UNION中较低的select语句的where子句中使用upper select语句的ID

时间:2013-05-15 13:38:55

标签: sql sql-server-2008 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)

所以这就是我刚尝试过的,我得到一个错误,即t1.ID无法绑定。这意味着我无法使用第二个中第一个选择的数据。

有没有办法可以使用第二个选择中第一个选择的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链接到第一个选择中包含的记录之一

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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')