通过组连接两个表

发布于 2024-12-22 01:58:48 字数 519 浏览 3 评论 0原文

我需要帮助查询连接旅馆(宿舍)数据库的两个表:

房间 - 房间 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失去的东西太少 2024-12-29 01:58:48

选项 1

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
     AND h.h_status= 'active'
GROUP BY h.h_roomno

选项 2

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' or H.H_Status is null)
GROUP BY h.h_roomno

问题是您的 where 子句排除了 t_rooms 中的记录,因为 t_hostelers 中没有记录。要更正,您需要在连接上应用过滤器,以便它仅适用于 t_hostelers 或在 where 子句中包含 NULL 结果。

Option 1

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
     AND h.h_status= 'active'
GROUP BY h.h_roomno

Option 2

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' or H.H_Status is null)
GROUP BY h.h_roomno

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文