[英]How to using INNER JOIN if one table is empty or no data
I have two tables; 我有两个桌子。 room
and reservation
. room
和reservation
。
data on room
room
数据
id_room | name_room | available_room
1 Class3 6
2 Class2 8
3 Class1 6
data on reservation
is empty reservation
数据为空
id_reservation | id_room | reserved_qty | checkin_date | checkout_date
1
2
3
If the guest wants to book a room, the website will display all the available room during data on table reservation
is empty (like table above), but, if there is data on table reservation
then the website will show remaining quantity of room (result from reduction between room.available_room
reservation.reserved_qty
( room.available_room
- reservation.reserved_qty
)) according to the date of booking and date already booked ( checkin_date
and checkout_date
). 如果客人想要预订房间,网站将显示所有可用的房间中的表中的数据reservation
为空(如表),但是,如果有上表中的数据reservation
,则网站将显示的房间剩余量(结果从减少之间room.available_room
reservation.reserved_qty
( room.available_room
- reservation.reserved_qty
))根据预定和日期的已经预定的日期( checkin_date
和checkout_date
)。
I don't understand why you would have "defective" rows in the reservation
table where the id_room
column is NULL
. 我不明白为什么您的reservation
表中id_room
NULL
行会有“有缺陷的”行。 But that doesn't change the proposed solution, since those defective rows would simply be disregarded, since a NULL
value for id_room
would never successfully join anything. 但这并不会改变建议的解决方案,因为那些有缺陷的行将被忽略,因为id_room
的NULL
值将永远不会成功地加入任何内容。
What you want is an OUTER JOIN
instead of an INNER JOIN
, so that the lack of a reservation doesn't prevent a room from appearing in the result. 您想要的是OUTER JOIN
而不是INNER JOIN
,因此缺少保留不会阻止房间出现在结果中。
SELECT room.id_room
, room.name_room
, room.available_room - SUM(COALESCE(reservation.reserved_qty, 0)) AS remaining_rooms
FROM room
LEFT OUTER JOIN reservation
ON room.id_room = reservation.id_room
WHERE
checkin_date IS NULL OR
@day BETWEEN checkin_date AND checkout_date
GROUP BY room.id_room, room.name_room;
The comment by @Thilo is sensible, since you might not really have records in the reservation
table which are just sitting there emtpy. @Thilo的注释是明智的,因为您可能没有真正在reservation
表中reservation
空的记录。 But if you are, one way to deal with "empty" data would be to use the COALSECE()
function when computing the difference: 但是,如果是这样,处理“空”数据的一种方法是在计算差异时使用COALSECE()
函数:
SELECT r1.id_room, r1.name_room,
r1.available_room - COALESCE(r2.reserved_qty, 0) AS numAvailable
FROM room r1
INNER JOIN reservation r2
ON r1.id_room = r2.id_room
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.