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.
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.
But thank you, unfortunately, made mistakes, decided to send me chat gpt.
thought that would be too complex for him but after three he managed to:
UPDATE posts INNER JOIN accounts ON posts.username = accounts.username SET posts.user_id = accounts.user_id
I’m sorry I couldn’t help you, but I’m glad it worked out.
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)
;