2

我有两张桌子。一个用于客户,另一个用于房间。我想使用具有以下要求的 mysql 检索房间..

  1. 特定房间中的客户数量少于房间表中的头部
  2. 房间不在客户表中

您可以查看此粘贴 http://pastebin.com/WgTtkQvD

如您所见,只有房间 1 不在预期结果中,因为它的“头部”和该房间的总客户数相等

房间 2 有 3 个顾客,比房间 2 的“头”少

房间 3 和 4 处于预期结果中,因为还没有人占用它

4

4 回答 4

5
SELECT   Rooms.id AS room_id,
         COUNT(Customer.id) AS occupied,
         Rooms.head AS total_head,
         Rooms.head - COUNT(Customer.id) AS remaining_head
FROM     Rooms LEFT JOIN Customer ON Customer.room_id = Rooms.id
GROUP BY Rooms.id
HAVING   remaining_head > 0

sqlfiddle上查看。

于 2012-07-25T08:23:34.580 回答
0

以下应该可以解决问题:

SELECT r.id, COUNT(c.id), r.head, r.head - COUNT(c.id) FROM Rooms AS r LEFT JOIN Customer AS c ON r.id = c.room_id WHERE r.head <= COUNT(c.id) GROUP BY r.id

我没有完全理解你的问题,而且我还没有在真正的数据库上尝试过这个,所以可能会有一些小故障需要解决。评论它任何更多的问题出现。

于 2012-07-25T08:22:26.830 回答
0

让我知道这个是否奏效

select r.id,c.occ_cnt as occupied,r.head as total_head,r.head - c.occ_cnt as       remaining_head
from room r,
(
select room_id,count(id) as occ_cnt
from customer
group by room_id
) c
where r.id = c.room_id
于 2012-07-25T08:24:54.757 回答
0

试试这个

select 
    r.id,coalesce(ct.counting,0) as occupied,r.head as total_head,
    r.head-coalesce(ct.counting,0)  as remaining_head
from
    rooms as r left join
(
    select room_id,count(id) as counting from customer as ct 
    group by room_id
) as ct on r.id=ct.room_id
where r.head-coalesce(ct.counting,0)>0
于 2012-07-25T08:28:30.613 回答