我会通过编写自定义 sql 来解决这个问题。对于 postgres 我可以做这样的事情
select * from
(select row_number() over(order by id) as row_num, *
from calorie
where user_id = 12345
order by id) as q
where row_num % ((select count(*)
from calorie
where user_id = 12345)/30) = 0
在这里,首先我查询了一个用户的整个查询并给他们 row_numbers
select row_number() over(order by id) as row_num, *
from calorie
where user_id = 12345
order by id
然后我发现了行之间的距离:
((select count(*)
from calorie
where user_id = 12345)/30)
这是 30 行,如果我得到的 30 行少,它会被零除。然后我得到了唯一可以被 row_distance 整除的行
row_num % row_distance = 0
您也可以使用对我来说似乎更容易的采样。也适用于少于 30 的行号
select *
from calorie
where user_id = 12345
order by random()
limit 30