对于另一个选择查询,使用where子句中的查询返回值

时间:2016-06-30 14:08:46

标签: sql sql-server

我有两张桌子,如下所示。

tblId

Id      Name
1A      James
23      Holly
33      Rob

tblData

Date          Score     Name
2016-06-01    3.5       James
2016-06-01    4.5       Holly
2016-06-01    5.5       Rob
2016-06-01    2.5       James
2016-06-01    3.5       Holly
2016-06-01    6.5       Rob
...
2016-06-01    7.5       James
2016-06-01    11.5      Holly
2016-06-01    1.5       Rob

我已经编写了下面的查询,但它并不像tick.Name位那样说多部分标识符无法绑定。

我知道

只会返回一条记录
select Name 
from tblId 
where Id = 33 

查询。在我的下一个select语句的where部分中使用此值的最佳方法是什么?

;with tick as
(
    select Name from tblId where Id = 33
)
select Date, Score 
from tblData
where Name = tick.Name and Date >= '2016-06-01'
order by Date

4 个答案:

答案 0 :(得分:2)

您考虑过join吗?

with tick as (
    select Name from tblId where Id = 33
   )
select t.Date, t.Score
from tblData t join
     tick
     on t.name = tick.name
where t.Date >= '2016-06-01'
order by t.Date

答案 1 :(得分:1)

试试这个,

select Date, Score from tblData td
where EXISTS (select 1 from tblId  t where t.Id = 33 AND td.Name = t.Name )
and Date >= '2016-06-01'
order by Date

答案 2 :(得分:1)

Select Date, Score from tblData
 where Name in (select Name from tblId where Id = 33) 
   and Date >= '2016-06-01'
 order by Date

答案 3 :(得分:0)

您可能还会考虑使用变量而不是CTE,因为您要从其他表中选择ID,这将始终只为您提供一个值。