How to merge these queries into 1 using subquery

2019-09-19 12:33发布

问题:

 Select * from HotelPerson 
 Where RoomID IN (select ID from HotelRoom Where BookingID = 36 )

 Select * from HotelCancelationPolicy 
 Where RoomID IN (select ID from HotelRoom Where BookingID = 36 )

How can I merge these both queries into 1 query ?

回答1:

This will give you all the columns from both tables in one table.

SELECT * 
FROM HotelPerson A, HotelCancelationPolicy B
WHERE A.RoomID = B.RoomID
AND A.RoomID IN (SELECT ID FROM HotelRoom WHERE BookingID = 36)


回答2:

Use UNION to Get Distinct elements or UNION ALL for all rows from both tables

 Select * from HotelPerson 
 Where RoomID IN (select ID from HotelRoom Where BookingID = 36 )
 UNION ALL
 Select * from HotelCancelationPolicy 
 Where RoomID IN (select ID from HotelRoom Where BookingID = 36 )


回答3:

I guess you want to join the two tables:

    select * 
      from HotelPerson hp
inner join HotelCancelationPolicy hcp
        on hp.RoomId = hcp.RoomId
     where hp.RoomID IN (select ID 
                           from HotelRoom 
                          where BookingID = 36 )