如何从2个表中减去乘数行? MySQL的

时间:2013-02-01 17:45:28

标签: mysql subtraction

我一直试图寻找一种方法从2个表中减去乘数行?因为我不断从mySQL工作台收到错误。

我有2个表hotelhotel_stay

我需要获得独特房间的数量,然后减去个人容量

+--------------------+------------------+
hotel_stay
+--------------------+------------------+
room (PK)
99
99
10
10
10

+--------------------+------------------+
hotel  
+--------------------+------------------+ 
room(FK)  |   capacity
99        |   10
10        |   12

输出将与酒店位于同一桌面上,或者我将向我们提供AS?

room | capacity
99   | 8      
10   | 9   

1 个答案:

答案 0 :(得分:1)

我不确定我完全理解你的问题。但是你可以用这样的东西来获得每个房间的总容量:

select h.room, 
   (h.capacity - hs.TotalBooked) as Capacity
from hotel h
inner join 
(
    select COUNT(room) as TotalBooked, 
       Room
    from hotel_stay
    group by room
) hs
    on h.room = hs.room

SQL Fiddle with Demo。这将返回结果:

| ROOM | CAPACITY |
-------------------
|   10 |        9 |
|   99 |        8 |