我正在尝试获取所有房间,并按每个房间的用户数量订购。
进入房间的每个用户,存储在表格轮盘中,但我需要在90秒前添加的行。
此查询返回按用户数排序的房间,但如果相应轮盘的数量为零,则不会返回空间,但我希望获得所有房间。
scope :with_users_in, -> { select("rooms.id, rooms.title, rooms.creation_time, rooms.room_life, count(roulettes.id) AS listens_count").
joins("LEFT OUTER JOIN roulettes ON roulettes.section_id = rooms.id").
group("rooms.id").
order("listens_count DESC").
where("roulettes.time > (? - 90)", Time.now.to_i)
}
如何修改我的查询?
例如,如果像这样重写我的范围:
scope :with_users_in, -> { select("rooms.id, rooms.title, rooms.creation_time, rooms.room_life, count(roulettes.id) AS listens_count").
joins("LEFT OUTER JOIN roulettes ON roulettes.section_id = rooms.id").
where("roulettes.time > (? - 900000) OR roulettes.time IS NULL", Time.now.to_i).
group("rooms.id").
order("listens_count DESC")
}
我得到了这个json:
[{"id":1,"title":"fdf","creation_time":1442706728,"room_life":20000300,"url":"http://localhost:3000/rooms/1.json","listens_count":2}]
但对于原始查询,我得到[]
。因为最后进入房间的时间比90秒还多。我希望它返回相同的内容,而不是listens_count:2
获取listens_count:0
生成的代码
Room Load (0.3ms) SELECT rooms.id, rooms.title, rooms.creation_time,
rooms.room_life, count(roulettes.id) AS listens_count FROM "rooms" LEFT
OUTER JOIN roulettes ON roulettes.section_id = rooms.id WHERE
(roulettes.time > (1442941851 -90) OR roulettes.time IS NULL) GROUP BY
rooms.id ORDER BY listens_count DESC LIMIT 20 OFFSET 0