【发布时间】:2021-06-04 22:30:53
【问题描述】:
我真的很挣扎如何实现将通过示例进行最佳描述的要求。 尽管我对 postgres 的解决方案感兴趣,但请考虑将以下所有内容都用伪代码编写。
| id | id_for_user | note | created_by |
|---|---|---|---|
| 1 | 1 | Buy milk | 1 |
| 1 | 2 | Winter tyres | 1 |
| 1 | 3 | Read for 1h | 1 |
| 2 | 1 | Clean dishes | 2 |
| 2 | 2 | Learn how magnets work | 2 |
INSERT INTO notes VALUES (note: 'Learn icelandic', created_by: 1);
| id | id_for_user | note | created_by |
|---|---|---|---|
| 1 | 1 | Buy milk | 1 |
| 2 | 2 | Winter tyres | 1 |
| 3 | 3 | Read for 1h | 1 |
| 4 | 1 | Clean dishes | 2 |
| 5 | 2 | Learn how magnets work | 2 |
| 6 | 4 | Learn Icelandic | 1 |
INSERT INTO notes VALUES (note: 'Are birds real?', created_by: 2);
| id | id_for_user | note | created_by |
|---|---|---|---|
| 1 | 1 | Buy milk | 1 |
| 2 | 2 | Winter tyres | 1 |
| 3 | 3 | Read for 1h | 1 |
| 4 | 1 | Clean dishes | 2 |
| 5 | 2 | Learn how magnets work | 2 |
| 6 | 4 | Learn Icelandic | 1 |
| 7 | 3 | Are birds real? | 2 |
我想实现这样的目标:
CREATE TABLE notes (
id SERIAL,
id_for_user INT DEFAULT nextval(created_by) -- Dynamic name for sequence so every user gets its own,
note VARCHAR,
created_by INT,
PRIMARY KEY(id, id_for_user),
CONSTRAINT fk_notes_created_by
FOREIGN KEY(created_by)
REFERENCES users(created_by)
);
让用户1 看到(注意id_for_user 在前端只是id)
| id | note |
|---|---|
| 1 | Buy milk |
| 2 | Winter tyres |
| 3 | Read for 1h |
| 4 | Learn Icelandic |
还有用户2
| id | note |
|---|---|
| 1 | Clean dishes |
| 2 | Learn how magnets work |
| 3 | Are birds real? |
基本上我想为每个用户设置自动递增的字段。
然后我也可能会根据哪个用户提出请求,通过id_for_user 在后端填充create_by 来查询记录。
这样的事情可能吗?我有哪些选择?我真的很想在数据库级别上有这个逻辑。
【问题讨论】:
-
这不是自动递增列的工作方式。
-
@GordonLinoff 很高兴知道如果您忽略该问题,您会推荐什么解决方案?
-
您可以有一个单独的表来存储“每个用户的最后一个 ID”。然后触发器可以填充值并增加相关表。插入是多线程的吗?如果是这种情况,您需要添加一些隔离(悲观或乐观锁定)。
-
@TheImpaler 我很难相信没有简单的解决方案,但我不是数据库专家。难道我们不能利用我忘记提及的
created_at专栏吗?您知道插入记录的顺序并以某种方式计算新的id_for_user吗? -
@Hnus 在查询表时动态计算值很容易:一个简单的
ROW_NUMBER()窗口函数就可以解决问题。我以为您想在插入时保留新 ID。
标签: sql postgresql