mysql与count()比较列

时间:2012-07-25 08:12:46

标签: mysql count

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

  1. 特定房间的客户数量少于房间表中的客户数
  2. 房间不在客户表中
  3. 你可以查看这个粘贴 http://pastebin.com/WgTtkQvD

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

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

    第3和第4房间是预期的结果,因为没有人“占用它”

4 个答案:

答案 0 :(得分: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上查看。

答案 1 :(得分: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

我没有完全理解你的问题,我实际上并没有在真正的数据库上尝试过这个问题,因此可能会有一些问题需要解决。再评论它出现了问题。

答案 2 :(得分: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

答案 3 :(得分: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