2015-12-21 59 views
1

我使用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"),所以這裏是我的問題,

  • 什麼是錯以上查詢?

  • 有沒有更好的方法來做到這一點?怎麼樣?

  • 有什麼可以改進的?

+0

注意:你的'last_message'有一個自然的關鍵問題。 last_message爲誰/從誰? (可能需要唯一) – joop

+0

'last_message'存儲特定聊天的最後一條消息,無論發送還是接收都無關緊要。 – zola

回答

0

使用CTE:

WITH toinsert as (
     INSERT INTO messages (contact, direction, body) 
      VALUES (9, 'sent', 'hello there') 
      RETURNING id 
    ) 
INSERT INTO last_message (chat, message) 
    SELECT 9, id 
    FROM toinsert; 
-1

步驟1

drop table last_message 

你可以得到這樣的最後一條消息:

select contact, direction, body 
from messages 
join 
(select chat, max(time) maxTime 
from messages 
group by chat 
) temp on messages.chat = temp.chat 
and time = maxTime 

您可以創建一個視圖或什麼有了這個邏輯,無論你的要求是怎樣的。