需要多个查询?

时间:2017-04-10 08:43:50

标签: mysql

我有三张桌子: - 房间:房间信息 - 床:房间内每张床(类型,...)的信息与房间ID相关联 - 分配:分配给一个房间的房间床位数的信息(一个房间可以分2组)

我想要一张床位数和一个房间分配床位数的清单

样品:

SELECT 
COUNT(beds.id) AS beds
FROM rooms 
JOIN beds ON rooms.id=beds.roomID 
WHERE rooms.id='124'

给出房间的床位数(8)。

SELECT
SUM(requestsAllocations.bedsAllocated) AS allocated,
from rooms 
join requestsAllocations on requestsAllocations.roomID=rooms.id
where rooms.id='124'

给我房间分配床位的数量:7(1 + 6)

SELECT
COUNT(beds.id) AS beds,
SUM(requestsAllocations.bedsAllocated) AS allocated
FROM rooms 
JOIN requestsAllocations ON requestsAllocations.roomID=rooms.id
JOIN beds ON rooms.id=beds.roomID
WHERE rooms.id='124'

给了我:

beds | allocated
----------------
16   | 56
  • 16张病床(由于分配表中的2条记录计算两次)
  • 56张床(7 * 8 = 56)

如何进行查询以获得正确的结果?

beds | allocated
----------------
8    | 7

谢谢!

2 个答案:

答案 0 :(得分:0)

要获得正确数量的床位,您只需为count

添加一个独特的床位即可
COUNT(distinct beds.id) AS beds

为避免分配床位的倍增,您可以使用

等解决方法
SUM(requestsAllocations.bedsAllocated) / COUNT(distinct beds.id) as allocated

最终查询将是

SELECT  COUNT(distinct t3.id) AS beds,
        SUM(t2.bedsAllocated) / COUNT(distinct t3.id) AS allocated
FROM    rooms t1
JOIN    requestsAllocations t2
ON      t2.roomID = t1.id
JOIN    beds t3
ON      t1.id = t3.roomID
WHERE   t1.id='124'

我还为你的表提供别名以提高可读性

答案 1 :(得分:0)

您必须在子查询中至少执行一个聚合(countsum),以便重复记录不会影响聚合结果。或者您可以简单地在选择列表中聚合两个相关的子查询:

select rooms.id,
       (select count(*) from beds where beds.roomID=rooms.id) as bed_count,
       (select sum(bedsAllocated) from requestsAllocations where requestsAllocations.roomID=rooms.id) as allocated_count
from rooms