我使用postgreSQL
用於存儲聊天記錄,我有這個示例模式:使用嵌套INSERT INTO的SQL?
CREATE TABLE contacts (
"id" BIGSERIAL PRIMARY KEY,
"user" BIGINT NOT NULL,
"contact" BIGINT NOT NULL,
"savedAs" VARCHAR(36),
CONSTRAINT user_fk FOREIGN KEY("user") REFERENCES users("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT contact_fk FOREIGN KEY("contact") REFERENCES users("id") ON DELETE CASCADE ON UPDATE CASCADE,
UNIQUE("user", "contact")
);
CREATE TABLE messages (
"id" BIGSERIAL PRIMARY KEY,
"contact" BIGINT NOT NULL,
"direction" direction_type NOT NULL,
"type" message_type default 'text',
"body" VARCHAR(1000) NULL,
"status" status_type DEFAULT 'none',
"time" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT contact_fk FOREIGN KEY("contact") REFERENCES contacts("id") ON DELETE CASCADE
);
CREATE TABLE last_message (
"id" BIGSERIAL PRIMARY KEY,
"chat" BIGINT NOT NULL UNIQUE,
"message" BIGINT NOT NULL,
CONSTRAINT message_fk FOREIGN KEY("message") REFERENCES messages("id"),
CONSTRAINT chat_fk FOREIGN KEY("chat") REFERENCES contacts("id") ON DELETE CASCADE
);
我想要做什麼,是存儲的最後一條消息在last_message
表中的特定聊天。我想這樣做這樣的(但不工作)的:
INSERT INTO last_message (chat, message) VALUES (
9,
(INSERT INTO messages (contact, direction, body) VALUES (9, 'sent', 'hello there') RETURNING id)
)
但我得到一個語法錯誤(syntax error at or near "into"
),所以這裏是我的問題,
什麼是錯以上查詢?
有沒有更好的方法來做到這一點?怎麼樣?
有什麼可以改進的?
注意:你的'last_message'有一個自然的關鍵問題。 last_message爲誰/從誰? (可能需要唯一) – joop
'last_message'存儲特定聊天的最後一條消息,無論發送還是接收都無關緊要。 – zola