我是SQL新手。
在postgres中使用jsonb时我很啰嗦。
这是我的sql文件:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE Users (
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
name text NOT NULL
);
CREATE TABLE Images (
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
url
);
CREATE TABLE Posts (
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
title text,
user_id uuid,
content jsonb
);
DO $$
DECLARE user_id UUID;
DECLARE image_id UUID;
BEGIN
INSERT INTO users (name) VALUES ('John') RETURNING id INTO user_id;
INSERT INTO images (url) VALUES ('http://xxx') RETURNING id INTO image_id;
INSERT INTO posts (title, user_id, content) VALUES (
'Learning PG',
user_id,
'[ { "type": "image", "image_id": "' || image_id || '" }, { "type": "text", "text": "Hello Postgres" } ]'
);
END $$;
然而,它会抛出错误,如:
psql:test.sql:53: ERROR: column "content" is of type jsonb but expression is of type uuid
LINE 3: image_id
我只想获得以下数据结构:
{
id: '109cf06c-17d8-4ffe-9c46-de4cc29e6353',
title: 'Learning PG',
user_id: 'b8aa2928-4fe1-4522-87b8-4dcdfe5cce0c',
content: [
{ type: 'image', image_id: '7454360f-2763-480f-9207-fcdc1787db9b' },
{ type: 'text', text: 'Hello Postgres' }
]
}
如何实施此要求?感谢。
答案 0 :(得分:1)
尝试在插入期间将content
转换为jsonb
:
INSERT INTO posts (title, user_id, content)
VALUES (
'Learning PG',
user_id,
'[ { "type": "image", "image_id": "' || image_id || '" }, { "type": "text", "text": "Hello Postgres" } ]'::jsonb
);