postgresql 这两个查询可以优化为一个查询吗?

whhtz7ly  于 2022-12-12  发布在  PostgreSQL
关注(0)|答案(1)|浏览(125)

给定表:

create table entries
(
    id           integer generated always as identity
        constraint entries_pk
            primary key,
    name         text    not null,
    description  text,
    type         integer not null
);

create table tasks
(
    id          integer generated always as identity
        constraint tasks_pk
            primary key,
    channel_id  bigint               not null,
    type        integer              not null,
    is_active   boolean default true not null
);

我现在有两个不同的疑问。第一:

SELECT id FROM tasks WHERE is_active = true;

然后,* 每个结果一次 * 从最后一个查询:

SELECT t.channel_id, e.name, e.description
FROM tasks t
JOIN entries e ON t.type = e.type
WHERE t.id = :task_id
ORDER BY random()
LIMIT 1;

换句话说,我想要一个单个随机entry * 用于每个 * 活动task
这是否可以在单个查询中完成,同时保持对每个任务的限制?

wnrlj8wa

wnrlj8wa1#

当然,使用DISTINCT ON

SELECT DISTINCT ON (t.id)
       t.id, t.channel_id, e.name, e.description
FROM tasks t
JOIN entries e USING (type)
ORDER BY t.id, random();

相关问题