1

I've being trying to update a row with a value from another table but I keep getting the same error:

table name "chats" specified more than once

I'm trying to insert a row into the messages table, and then use that timestamp (message_timestamp) to update the last_updated field in the chats table.

Any help would be appreciated! Been stuck on this for a day now:

WITH result AS 
(INSERT INTO messages (user_id, chat_id, message_timestamp, users_read, message_text) 
VALUES ($1, $2, NOW(), '{}', $3) RETURNING message_timestamp, chat_id)

UPDATE chats SET chats.last_updated=result.message_timestamp FROM result, chats WHERE chats.id=result.chat_id;

Edit:

On the other hand, removing chats from my FROM clause as so:

UPDATE chats SET chats.last_updated=result.message_timestamp FROM result WHERE chats.id=result.chat_id;

results in a different error:

column "chats" of relation "chats" does not exist

Which is weird considering I never call chats.chats

Edit 2: Create statement for the chat table:

CREATE TABLE IF NOT EXISTS chats (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  chat_name VARCHAR,
  last_message TIMESTAMP NOT NULL
);
3
  • hey @Adrian Coutsoftides : Can you share chats table schema or the create statement? Commented Jan 2, 2021 at 14:28
  • @AbhishekGinani sure, updating now Commented Jan 2, 2021 at 14:32
  • 2
    UPDATE chats SET last_updated=result.message_timestamp FROM result WHERE chats.id=result.chat_id; Commented Jan 2, 2021 at 14:48

1 Answer 1

1

From UPDATE:

Do not include the table's name in the specification of a target column

So the column last_updated that you want to update should not be qualified with the table's name like chats.last_updated:

UPDATE chats 
SET last_updated = result.message_timestamp 
FROM result 
WHERE chats.id = result.chat_id;

See a simplified demo.

Sign up to request clarification or add additional context in comments.

1 Comment

Damn; that's weird considering all other queries let you specify the column name to disambiguate the request. Guess now I know!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.