MySQL选择信息

时间:2013-11-13 13:05:51

标签: mysql database

所以我需要帮助搜索一些信息。我正在寻找房间里有自由空间的房间。我添加了表格之前和之后的图片。我希望有足够的信息:) enter image description here

3 个答案:

答案 0 :(得分:0)

首先找出每个房间有多少人:

SELECT door_nr
     , Count(*) As number_of_occupants
FROM   people
GROUP
    BY door_nr

然后我们可以使用此查询并根据匹配的rooms值将其重新连接到door_nr表。

SELECT rooms.door_nr
     , rooms.space As capacity
     , room_usage.number_of_occupants
     , rooms.space - room_usage.number_of_occupants As free_space
FROM   rooms
 LEFT
  JOIN (
        SELECT door_nr
             , Count(*) As number_of_occupants
        FROM   people
        GROUP
            BY door_nr
       ) As room_usage
    ON room_usage.door_nr = rooms.door_nr

答案 1 :(得分:0)

SELECT Door_Nr, COUNT(*) FROM People GROUP BY Door_Nr

会告诉你房间里的人数。

有了(My)SQL的基本工作知识,你应该能够弄清楚其余部分吗? 否则,请询问具体问题。

答案 2 :(得分:0)

select r.door_nr, 
       r.space - sum(p.name is not null) as free
from rooms r
left join people p on p.door_nr = r.door_nr
group by r.door_nr, r.space
having free > 0

SQLFiddle demo