我想将用户的设置存储在 postgresql 数据库中。 我想保留其设置的完整历史记录,并且还能够查询给定用户的最新设置。
我尝试将设置存储在如下表中:
CREATE TABLE customer (
customer_id INTEGER PRIMARY KEY,
name VARCHAR NOT NULL
);
CREATE TABLE customer_settings (
customer_id INTEGER REFERENCES customer NOT NULL,
sequence INTEGER NOT NULL, -- start at 1 and increase, set by the application
settings JSONB NOT NULL,
PRIMARY KEY(customer_id, sequence)
);
因此 customer_settings 是每个客户的仅附加日志。
然后,为了查询最新设置,我使用一个长查询,该查询将执行子查询来选择给定 customer_id
的最大 sequence
,然后选择该 id 的设置.
这太尴尬了!请问有没有更好的办法?我可以使用 View 或触发器来创建第二个表latest_customer_settings
吗??
最佳答案
您可以进行查看。要在 Postgres 中获取多个客户的设置,我建议:
select distinct on (customer_id)
from customer_settings cs
order by customer_id, sequence desc;
对于此查询,我建议在 customer_settings(customer_id,equence desc)
上建立索引。
此外,如果您可以为所有客户处理一个总体序列号,您可以让 Postgres 生成序列。
CREATE TABLE customer_settings (
customer_settings_id bigserial primary key,
customer_id INTEGER REFERENCES customer NOT NULL,
settings JSONB NOT NULL
);
然后,应用程序不需要设置序列
号。您只需将 customer_id
和 settings
插入表中即可。
让应用程序维护此信息有一些缺点。首先,应用程序必须先从数据库中读取数据,然后才能将任何内容插入表中。其次,如果多个线程同时更新表(在本例中是针对同一客户),则可能会出现竞争条件。
关于sql - postgresql 中仅附加日志的最新条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56096235/