Nik*_*ilo 6 mysql sql subquery
我正在开发酒店房间预订系统。
该系统将包含一定数量的酒店,房间和room_categories。我已经有了这些东西的桌子。
目前,我需要构建一个查询以获取给定日期每个房间类别的可用房间数量。
我的房间表是这样的:
--------------------------------------------
| id | name | hotel_id |room_category_id|
--------------------------------------------
| 1 | Room #1 | 1 | 1 |
| 2 | Room #2 | 1 | 1 |
| 3 | Room #3 | 1 | 2 |
| 4 | Room #4 | 1 | 2 |
| 5 | Room #5 | 1 | 3 |
| 6 | Room #6 | 1 | 3 |
| 7 | Room #7 | 1 | 4 |
| 8 | Room #8 | 1 | 4 |
--------------------------------------------
Run Code Online (Sandbox Code Playgroud)
房间类别表是这样的:
--------------------------------------------
| id | name | hotel_id |room_category_id|
--------------------------------------------
| 1 | Room #1 | 1 | 1 |
| 2 | Room #2 | 1 | 1 |
| 3 | Room #3 | 1 | 2 |
| 4 | Room #4 | 1 | 2 |
| 5 | Room #5 | 1 | 3 |
| 6 | Room #6 | 1 | 3 |
| 7 | Room #7 | 1 | 4 |
| 8 | Room #8 | 1 | 4 |
--------------------------------------------
Run Code Online (Sandbox Code Playgroud)
预订表如下:
----------------------------------
| id | name | price | volume |
----------------------------------
| 1 | Standart | $100 | 2 |
| 2 | Comfort | $150 | 2 |
| 3 | Half Lux | $200 | 3 |
| 4 | Lux | $250 | 3 |
----------------------------------
Run Code Online (Sandbox Code Playgroud)
我正在尝试这个查询
------------------------------------------------------------------------
| id | booking_start | booking_end | room_id |room_category_id|hotel_id|
------------------------------------------------------------------------
| 1 | 2019-06-17 | 2019-07-17 | 1 | 1 | 1 |
| 2 | 2019-06-17 | 2019-07-17 | null | 2 | 1 |
| 3 | 2019-06-17 | 2019-07-17 | null | 3 | 1 |
------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
假设我每个类别有2个房间,每个类别有1个预订。该查询仅返回我没有任何预订的类别(在我的情况下,room_category = 4)。
-------------------
| name |quantity|
-------------------
|Standart| 2 |
-------------------
Run Code Online (Sandbox Code Playgroud)
我应该如何建立查询以获取正确的计数,如下所示:
|room_category|count|
---------------------
| Standart | 1 |
| Comfort | 1 |
| Half Lux | 1 |
| Lux | 2 |
---------------------
Run Code Online (Sandbox Code Playgroud)
您的问题对于“可用”的含义以及您想要的日期有点模糊。让我假设您想要按类别列出从 2019 年 6 月 17 日到 2019 年 7 月 28 日整个期间可用的房间数量(对我来说这似乎是很长一段时间,而且一家酒店有该房间)整个时期好像生意并不是很好)。
SELECT rc.name,
COUNT(b.room_id IS NULL) as quantity
FROM rooms r JOIN
room_categories rc
ON rc.room_category_id = r.id LEFT JOIN
bookings b
ON b.room_id = r.room_id AND
b.booking_start <= '2019-07-28' AND
b.booking_end >= '2019-06-17'
WHERE r.hotel_id = 1
GROUP BY rc.name
ORDER BY quantity DESC;
Run Code Online (Sandbox Code Playgroud)
匹配LEFT JOIN在该日期范围内有预订的任何预订。然后,外部查询对不匹配的行进行计数。请注意,过滤器不在子句中WHERE,因此您可以获得 的计数0。