假设我有一个表foo
,我想从每个类别中选择 N 行
create table foo(name text, category text);
name | category
------+----------
aaa | cat1
bbb | cat1
ccc | cat2
ddd | cat2
eee | cat2
现在我想从给定多个类别的 foo 中挑选
category | count
----------+-------
cat2 | 2
cat1 | 1
结果应该是 3 行(关系可以随机或按任何顺序解决)
name
------
ccc
ddd
aaa
-- wrong, not taking counts into account
with t as (select * from (values ('cat1', 1), ('cat2', 2)) as
t(category, count)) select name from foo, t where foo.category = t.category;
name
------
aaa
bbb
ccc
ddd
eee
我可以用多个查询来做到这一点,但我认为我遗漏了一些非常明显的东西,选择可以用一个查询来完成。
最佳答案
SELECT x.*
FROM categories c,
LATERAL (
select * FROM foo
where foo.category = c.category
ORDER BY random()
LIMIT c.count
) x
关于SQL 选择动态计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45359328/