Postgresql - 多个 select 条件
Postgresql - multiple select condition
我有 table 具有以下结构:
|id|author_id|name|type|created_at|updated_at
作为一种类型,我可以有 5 种不同的类型,(A、B、C、D、E)。
我需要一个 author_id 的查询数据库,我可以 select 只有最后更新的行 "type" A 和 B。以及 select 所有其他类型的行。
所以结果应该是这样的:
| id | author_id | name | type | created_at | updated_at
| 12 | 88 | lorem | A
| 45 | 88 | lorem | B
| 44 | 88 | lorem | C
| 154 | 88 | lorem | C
| 98 | 88 | lorem | C
| 856 | 88 | lorem | E
| 857 | 88 | lorem | E
单次查询可以吗?或者我需要使用两个查询?
谢谢
您可以尝试以下方法:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY "type" ORDER BY updated_at DESC) rn
FROM yourTable
)
SELECT id, author_id, name, "type", created_at, updated_at
FROM cte
WHERE
("type" IN ('A', 'B') AND rn = 1) OR
"type" NOT IN ('A', 'B');
此方法使用 ROW_NUMBER
查找所有类型的最新行。在 CTE 查询中,我们 select 仅 A
和 B
类型的最近更新行,但我们 select 所有其他类型的所有行。
假设 id
是 table 中的唯一键,您可以使用 distinct on
:
select distinct on(case when type in ('A', 'B') then type else id::text end) t.*
from mytable t
order by case when type in ('A', 'B') then type else id::text end, created_at desc, id
这使用条件表达式作为 distinct on
键,即 returns 如果是 A 或 B,则 type
或 id
用于其他值。因此,您获得类型 A 和 B 的前 1 个值,以及其他类型的所有其他值。
我在想:
(select distinct on (type) t.*
from t
where type in ('A', 'B')
order by type, created_at desc
) union all
select t.*
from t
where type not in ('A', 'B');
特别是,这可以很好地利用(type, created_at desc)
上的索引。
我有 table 具有以下结构:
|id|author_id|name|type|created_at|updated_at
作为一种类型,我可以有 5 种不同的类型,(A、B、C、D、E)。
我需要一个 author_id 的查询数据库,我可以 select 只有最后更新的行 "type" A 和 B。以及 select 所有其他类型的行。
所以结果应该是这样的:
| id | author_id | name | type | created_at | updated_at
| 12 | 88 | lorem | A
| 45 | 88 | lorem | B
| 44 | 88 | lorem | C
| 154 | 88 | lorem | C
| 98 | 88 | lorem | C
| 856 | 88 | lorem | E
| 857 | 88 | lorem | E
单次查询可以吗?或者我需要使用两个查询?
谢谢
您可以尝试以下方法:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY "type" ORDER BY updated_at DESC) rn
FROM yourTable
)
SELECT id, author_id, name, "type", created_at, updated_at
FROM cte
WHERE
("type" IN ('A', 'B') AND rn = 1) OR
"type" NOT IN ('A', 'B');
此方法使用 ROW_NUMBER
查找所有类型的最新行。在 CTE 查询中,我们 select 仅 A
和 B
类型的最近更新行,但我们 select 所有其他类型的所有行。
假设 id
是 table 中的唯一键,您可以使用 distinct on
:
select distinct on(case when type in ('A', 'B') then type else id::text end) t.*
from mytable t
order by case when type in ('A', 'B') then type else id::text end, created_at desc, id
这使用条件表达式作为 distinct on
键,即 returns 如果是 A 或 B,则 type
或 id
用于其他值。因此,您获得类型 A 和 B 的前 1 个值,以及其他类型的所有其他值。
我在想:
(select distinct on (type) t.*
from t
where type in ('A', 'B')
order by type, created_at desc
) union all
select t.*
from t
where type not in ('A', 'B');
特别是,这可以很好地利用(type, created_at desc)
上的索引。