为什么以下查询不会生成最受欢迎公寓的 ID 和地址?

Why wouldn't the following query produce the ids and addresses of the most popular apartments?

我有一个简单的数据库,其中一个 table 包含公寓,另一个包含对这些公寓感兴趣的人的 ID(或他们的 ID)。我正在尝试使用嵌套查询获取对公寓最感兴趣的人

select toh.t, toh.o, toh.h
from (
  select ok.houseid as t, va.houseaddress as o, count ( ok.customerid ) as h
  from house va
    inner join is_interested ok
      on va.houseid = ok.houseid
  group by t
) toh
group by toh.t
  having toh.h = max( toh.h )
;

这不符合我的要求。内部 select 应该给我取一个 table,其中包含 ID、地址,最后是对他们感兴趣的人的 ID 计数,按公寓 ID 分组,这个 id 做得很好。

因此问题很可能出在最后两行:

group by toh.t
  having toh.h = max( toh.h )

因为 return所有可用的公寓,无论有多少人对它们感兴趣。将其更改为

group by toh.t
  having toh.h > 1

为我选择了正确的公寓(目前最多有 2 人对上述公寓感兴趣)。看来我不完全理解函数 max 应该如何工作。 count return 不应该是一个整数,或者这首先与类型不匹配有关吗?因为看起来确实像。

对我来说,你指出的两行看起来像:

group by toh.t
having toh.h = max( toh.h )

具有以下含义:

  1. 通过 toh.t 键获取我的群组
  2. 在这些组中,仅显示值 toh.h 等于组 中该字段值的最大值的组 。如果我没看错,情况总是如此,因为组中 toh.t 中只有一个值。

我相信你想要的是在分组之前对所有toh.h取全局最大值,对吗?

你不能return你想要的最大值。
使用 CTEis_interested 获取所有计数,然后加入 house:

with 
  cte as (
    select houseid, count(customerid) counter
    from is_interested
    group by houseid
  )
select h.houseid, h.houseaddress, c.counter
from house h inner join (
  select * from cte
  where counter = (select max(counter) from cte)
) c on c.houseid = h.houseid