通过组连接两个表
我需要帮助查询连接旅馆(宿舍)数据库的两个表:
房间 - 房间 id、类别、租金、床位数量等
旅馆 - 旅馆 id、姓名、房间 id 等
我需要生成一个结果集所有房间、床位总数和入住人数。床位数量和免费床位数量等
这是我正在使用的查询:
SELECT r.R_ID , r.R_Beds, count(h.h_id), (r.r_beds-count(h.h_id)) ,
if((r.r_beds-count(h.h_id))>0, 'Available', 'Full' ) , r.r_rent
FROM T_Rooms r LEFT OUTER JOIN t_hostelers h
ON r.r_id = h.h_roomno
WHERE h.h_status= 'active'
GROUP BY h.h_roomno
但我只从 rooms 表中获取行,这些行在 hostelers 表中具有值。我还需要展示其他没有入住的房间。
请帮助我找出我的疏忽或错误。
I need help with a query joining two tables for a hostel (dorm) database:
Rooms - room id, category, rent, no of beds, etc
Hosteler - hosteler id, name, room id, etc
I need to generate a result set giving all the rooms, total no of beds and occupied no. of beds and free no of beds, etc
Here is the query I am using:
SELECT r.R_ID , r.R_Beds, count(h.h_id), (r.r_beds-count(h.h_id)) ,
if((r.r_beds-count(h.h_id))>0, 'Available', 'Full' ) , r.r_rent
FROM T_Rooms r LEFT OUTER JOIN t_hostelers h
ON r.r_id = h.h_roomno
WHERE h.h_status= 'active'
GROUP BY h.h_roomno
But I am getting only rows from rooms table which have a value in hostelers table. I need to show other rooms with no occupancy also.
Please help me find out my oversight or mistake.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
选项 1
选项 2
问题是您的 where 子句排除了 t_rooms 中的记录,因为 t_hostelers 中没有记录。要更正,您需要在连接上应用过滤器,以便它仅适用于 t_hostelers 或在 where 子句中包含 NULL 结果。
Option 1
Option 2
The problem is your where clause is excluding records from t_rooms because there is no record in t_hostelers. To correct you need to apply the filter on the join so it only applies to the t_hostelers OR include NULL results in a where clause.