0

数据:

表格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

链接表:

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 链接到第一个选择中包含的记录之一。

4

2 回答 2

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
于 2013-05-15T13:50:38.630 回答
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')
于 2013-05-15T13:47:10.480 回答