room | beds available | ****table room****
==================================
room1 | 4
room2 | 2
room3 | 4
room | occupant | ****table occupant****
==================================
room1 | arnold
room1 | berry
room2 | charles
room2 | daisy
room3 | eric
room3 | frank
room3 | greg
我希望获得以下输出:
没有。有床的房间:2 ||提供床铺的客房:1号房,3号房
我估计我需要
php代码段代码应如何显示?
答案 0 :(得分:1)
这些SQL查询可以解决问题。
请注意,您可以删除不需要的列以节省您正在处理的数据量...
select r.id AS 'room',
r.beds as 'total_beds',
count(o.occupant) as 'taken_beds',
r.beds-count(o.occupant) as 'free_beds'
FROM room r LEFT JOIN occupant o ON r.id = o.room
GROUP BY r.id
HAVING r.beds > count(o.occupant)
这只会返回未满的房间。
如果在任何其他时间点,您也希望返回完整的房间,只需删除" HAVING"条款
select r.id AS 'room',
r.beds as 'total_beds',
count(o.occupant) as 'taken_beds',
r.beds-count(o.occupant) as 'free_beds'
FROM room r LEFT JOIN occupant o ON r.id = o.room
GROUP BY r.id
答案 1 :(得分:0)
我认为这一切都可以通过一个简单的SQL查询来完成,看起来像这样:
["12/05/2014", "null", "null"]
["null", "12/07/2014", "null"]
["lesser than", "lesser than", "equal to"]
你可以使用' HAVING'子句,它与WHERE子句类似,但与聚合一起使用。我没有在你的确切表上运行这个确切的查询,所以可能会有一个拼写错误,但是,我希望查询应该做的是明确的。
答案 2 :(得分:0)
这样的地方你可以改变你需要的床位数。
SELECT r.*, COUNT(*) AS occupied, r.beds - COUNT(*) AS rest
FROM room r
LEFT JOIN occupant o ON r.room = o.room
GROUP BY r.room
HAVING r.beds - occupied >= 1
答案 3 :(得分:0)
MySQL提供GROUP_CONCAT
来汇总字符串:
select
count(*) as number_of_rooms,
group_concat(room) as rooms
from room r
where beds_available >
(
select count(*)
from occupant o
where o.room = r.room
);
选择可用床位数超过占用面积的房间,然后将结果行汇总到一行,其中包含可用房间数和一个房间名称以逗号分隔的字符串。