简体   繁体   中英

MySQL: complex query for hotel reservation service

here's my data:

table: rooms_available

    ID  date        user  room_id 
   ------------------------------
    1   2018-04-02  1     10
    2   2018-04-03  1     10
    3   2018-04-04  1     10

    4   2018-04-02  1     20
    5   2018-04-03  1     20
    6   2018-04-04  1     20

    7   2018-04-02  2     11
    8   2018-04-04  2     11

    9   2018-04-01  3     12
   10   2018-04-02  3     12
   11   2018-04-03  3     12
   12   2018-04-04  3     12
   13   2018-04-05  3     12

i'm trying to write a search function for searching for available rooms. for example, when searching from 2018-04-02 to 2018-04-04 the desired output would be:

user level: (for building the main result recordset)

user  rooms_available
---------------------
1     2
3     1

room level (per user):

user  room_id
-------------
1     10
1     20
3     12

i encountered several problems with my queries:

select * from rooms_available where date between '2018-04-02' AND '2018-04-04'

would also return the records from user 2 which is wrong as the date range is missing 2018-04-03. same as:

select * from rooms_available where (date='2018-04-02' OR date='2018-04-03' OR date='2018-04-04')

so the query needs to consider the amount of days/records for the full date range which would be 3. i've tried something like count(*) and HAVING but it didn't work as expected.

any ideas how to solve it? thanks

I think you want something like this for the rooms per user:

select user, room_id
from rooms_available
where date between '2018-04-02' AND '2018-04-04'
group by user, room_id
having count(*) = 3;  -- this is the number of days in the range

To get your first result, just use this as a subquery and aggregate again.

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