我正在尝试json_extract_path_text()使用citext模块制作不区分大小写的版本。
我希望这是一个围绕内置函数的简单包装器,唯一的区别是它接受citext作为第一个参数而不是json. 我希望这是对本机实现的直接传递,只需事先进行类型转换。这是我到目前为止所拥有的:
create extension citext;
create or replace function json_extract_path_text ( string citext, variadic params text[]) RETURNS text IMMUTABLE AS
$$
BEGIN
SELECT json_extract_path_text(string::json, params);
END;
$$
LANGUAGE 'plpgsql';
Run Code Online (Sandbox Code Playgroud)
但是,由于类型不匹配,这不能正常工作:
Run Code Online (Sandbox Code Playgroud)ERROR: function json_extract_path_text(json, text[]) does not exist LINE 1: SELECT json_extract_path_text(string::json, params) ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. QUERY: SELECT json_extract_path_text(string::json, params) CONTEXT: PL/pgSQL function json_extract_path_text(citext,text[]) line 3 …
考虑一个座位预订数据库。有 n 个座位的列表,每个座位都有一个属性is_booked。0 表示不是,1 表示是。任何更高的数字都会出现超额预订。
在不允许超额预订的情况下进行多次交易(每个交易将同时预订一组 y 个座位)的策略是什么?
我会简单地选择所有未预订的座位,选择其中 y 个随机选择的一组,全部预订,然后检查该预订是否正确(也就是 is_booked 的数量不超过一个,这将表示预订了座位的另一笔交易和提交),然后提交。否则中止并重试。
这是在 Postgres 中的 Read Committed 隔离级别上运行的。
我的问题的小提琴可以在https://dbfiddle.uk/?rdbms=postgres_10&fiddle=3cd9335fa07565960c1837aa65143685上找到。
我有一个简单的表格布局:
class
person: belongs to a class
Run Code Online (Sandbox Code Playgroud)
我想选择所有班级,对于每个班级,我想要按降序排列的所属人员的前两个人员标识符。
我通过以下查询解决了这个问题:
select c.identifier, array_agg(p.identifier order by p.name desc) as persons
from class as c
left join lateral (
select p.identifier, p.name
from person as p
where p.class_identifier = c.identifier
order by p.name desc
limit 2
) as p
on true
group by c.identifier
order by c.identifier
Run Code Online (Sandbox Code Playgroud)
注意:我可以在SELECT子句中使用相关子查询,但作为学习过程的一部分,我试图避免这种情况。
如您所见,我order by p.name desc在两个地方申请:
有没有办法避免这种情况?我的坚持:
首先,显然我不能删除order by子查询中的 ,因为这会给出一个不符合我上述要求的查询。
其次,我认为order by聚合函数中的 不能被遗漏,因为子查询的行顺序不一定保留在聚合函数中?
我应该重写查询吗?
在 PostgreSQL 9.6 我有一个T这样的表
category | id | data
---------+----+------
A | 1 | foo
A | 2 | bar
A | 3 | baz
B | 4 | eh
B | 5 | whatcomesafterfoobarbaz
Run Code Online (Sandbox Code Playgroud)
有一个视图V为我提供了数据T,所以它有列category, id, data。T本质上是 的物化视图V,除了我需要以比“刷新所有内容”更多的粒度来刷新它。
所以我会选择V例如
SELECT * FROM V WHERE category = 'A';
Run Code Online (Sandbox Code Playgroud)
或者
SELECT * FROM V WHERE category = 'A' AND id = 2;
Run Code Online (Sandbox Code Playgroud)
并T用任何data V …
postgresql ×4
concurrency ×2
aggregate ×1
array ×1
functions ×1
locking ×1
order-by ×1
parameter ×1
subquery ×1
update ×1