简体   繁体   中英

Query showing all records of one table and adding new field

So I have 3 tables which are:

Client = ClientID, ClientName,

Room = RoomID, RoomName

Booking = BookingID, RoomID, ClientID, Status (3 possible values: Booked, Checked-In, Checked-Out), CheckInDate, CheckOutDate

RoomID and ClientID has one-to-many relationship with the fields in booking table

My goal is to create a query that shows all of the rooms in the current time and show their status along with the information of the ocupant (if any) and their check in check out time of each room with these fields:

RoomStatus = RoomName, Status (4 possible values: Empty, Booked, Checked-In, Checked-Out (might be unnecessary since ocupant is no longer in the room)), ClientName, CheckInDate, CheckOutDate

I have managed to create simple query that using the relationships between the tables that shows all of the currently used room that shows all the information I needed. But the problem arise when I'm unable to show the unused room in the query. Since the status fields are in the booking table to keep it simple, the room table has no status field on its own to use.

I've attempted to make an empty query with showing all record of the room using the room id field and make new fields similar with the working ones that has null values and tried to left join and union it with the working one. However, left join only select similar record which only ends up showing the same thing as before and union provides duplicates. But I think this method to be "messy" if it does work.

So I'm open to any other method that is much better than my proposed method. Thank you very much.

I think this is what you are trying to achieve

select *
from @room c
left join 
(
select b.*
from @Room r
inner join @Booking b on r.RoomID = b.RoomID
inner join @Client c on c.ClientID = b.ClientID
where CheckInDate = '02/03/2016'
) a on a.RoomID = c.RoomID

In MS Access this can be achived in 2 steps. 1st step will create Query which display result of this query.

select b.*
from @Room r
inner join @Booking b on r.RoomID = b.RoomID
inner join @Client c on c.ClientID = b.ClientID
where CheckInDate = '02/03/2016'

in second step you will do the left join on above QUERY with table rooms. Displaying All records from table room and only those records from above query where join matches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM