Sql werte von einer tabelle auf die andere übertragen?

Zb ich hab eine datenbank in der sind zwei tabellen, eine heisst accounts eine heisst posts.

ein account hat eine einzigartige user_id & username bei jedem erstellten post soll das dabei stehen um später bei posts danach zu filtern was die Person gepostet hat.
aber habe das mit der „user_id“ erst später in posts eingefügt deswegen steht da überall 0.

Wie kann ich jetzt sagen das da wo username übereinstimmt soll die gleiche user_id auch bekommen.
Hat keinen krassen sinn dahinter wollte nur bisschen herum probieren und lernen mit sql bevor ich irgendeinen php code schreibe.
Bin nämlich leider ziemlich schlecht in sql

Ich mein das jetzt auch nicht zu gross ernst mit dem twitter instagram klon keine angst wegen sicherheitslücken.

(1 votes)
Loading...

Similar Posts

Subscribe
Notify of
4 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
M200M
1 year ago

I’m not the best, but that could help:

UPDATE posts

SET posts.user_id = accounts.user_id

FROM accounts

WHERE posts.username = accounts.username;

This instruction tells the database that it should update the “user_id” in the “posts” table by using the “user_id” from the “accounts” table when the “username” is in both tables.

Don’t forget to make a backup before that if something goes wrong, as UPDATE instructions can change data in the database.

M200M
1 year ago
Reply to  FritzboxCable

I’m sorry I couldn’t help you, but I’m glad it worked out.

Suboptimierer
1 year ago

Your approach was not completely wrong if you compare it with the ChatGPT solution.

Your approach goes towards Subselect:

UPDATE posts
SET posts.user_id = (select) accounts.user_id
FROM accounts
WHERE posts.username = accounts.username)
;