数组中对象的自动增量ID

时间:2019-06-02 12:57:50

标签: sql postgresql

我需要在PostgreSQL中存储对象数组。对象的结构应类似于

{
  "id": 1
  "title": "XYZ",
  "content": "abcabc"
}

我的问题是如何自动增加ID?

表的结构看起来像

user_id | user_name | notes

notes列应存储对象(注释)的数组。 什么是最好的方法,什么是最好的数据类型(json,jsonb,  json [],jsonb [])? 我正在使用flask和postgresql(11)。

1 个答案:

答案 0 :(得分:0)

使用单独的表格:

create table user_notes (
    user_notes_id serial primary key,
    user_id int references users(user_id),
    title text,
    content text,
    created_at timestamp default now()
);

如果要枚举特定用户的注释,请使用row_number()

select un.*, row_number() over (partition by un.user_id order by un.user_notes_id) as seqnum
from user_notes un
where un.user_id = ?;