如何简化这个SQL查询?

时间:2015-03-20 18:34:16

标签: sql-server database

update Room set Selected = 1 where Room_ID = 
(select Room_ID from Room_Rev where Rev_ID = 
(select Rev_ID from Room_Rev where Room_ID = 'ROM0001'
and (Start_Date<='2015-03-20' and End_Date>'2015-03-20')))

有人可以帮我简化此查询吗?

我想从Room_Rev中选择许多Room_ID,其中相同的Rev_ID与Room_ID =&#39; ROM0001&#39;,而不是所有Room_ID将用于更新所选 Room和Room_Rev是一对多的关系

2 个答案:

答案 0 :(得分:1)

您可以使用以下联接:

update r
set r.Selected = 1
from Room r 
inner join Room_Rev rr on r.Room_ID = rr.Room_ID
where rr.Room_ID = 'ROM0001'
and (rr.Start_Date<='2015-03-20' and rr.End_Date>'2015-03-20')

答案 1 :(得分:1)

join中使用Update...Select

update Room set Selected = 1 
from  
Room join Room_Rev rr on Room.Room_ID = rr.Room_ID and Room.Room_ID='ROM0001'
and Room.Start_Date<='2015-03-20' and Room.End_Date>'2015-03-20'

或使用where exists

update Room set Selected = 1 
where exisis (select Rev_ID from Room_Rev where Room_ID = 'ROM0001')
and Room_ID='ROM0001'
and (Start_Date<='2015-03-20' and End_Date>'2015-03-20')