计算字段总数与另一个表列值

时间:2016-04-29 13:38:03

标签: php mysql sql

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号房

我估计我需要

  1. 为每个独特的房间存储计数*并将计数存储为数组
  2. 针对此阵列减去每个房间可用的床位
  3. 显示结果时的房间名称> 0
  4. php代码段代码应如何显示?

4 个答案:

答案 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)

这只会返回未满的房间。

MySQL Result

如果在任何其他时间点,您也希望返回完整的房间,只需删除" 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

MySQL Result without HAVING clause

答案 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
);

选择可用床位数超过占用面积的房间,然后将结果行汇总到一行,其中包含可用房间数和一个房间名称以逗号分隔的字符串。