My project is growing and need to expand from a single table to two.
I have posts, and each post has an author. Currently the author is just a column in posts, but I have made an new table called authors. I would like to populate the new table with all unique instances of authors and replace the author values in the posts table with the new author ids.
Is there some sql magic that can help me do this? My post table is 30k entries so I would like to avoid doing it manually ;)
thanks!
You can move rows from one table to another with the help of INSERT INTO SELECT statement.
UPDATE syntax:UPDATE table_name SET column_name = value WHERE condition; To perform the above function, we can set the column name to be equal to the data present in the other table, and in the condition of the WHERE clause, we can match the ID. we can use the following command to create a database called geeks.
Create the new table Authors
.
CREATE TABLE Authors (
author_id INT AUTO_INCREMENT PRIMARY KEY,
author_name VARCHAR(20)
);
Populate Authors
with the set of distinct authors from Posts
.
INSERT INTO Authors (author_name)
SELECT DISTINCT author_name FROM Posts;
Add an author_id column to Posts, which references Authors.
ALTER TABLE Posts ADD COLUMN author_id INT,
ADD FOREIGN KEY (author_id) REFERENCES Authors(author_id);
Update Posts
with the corresponding author_id values, based on an (inefficient) join based on the author_name in each table. MySQL supports multi-table UPDATE syntax, which is not standard SQL, but it's very handy for these situations.
UPDATE Posts JOIN Authors USING (author_name)
SET Posts.author_id = Authors.author_id;
Drop the now-redundant author_name from Posts, and optionally make author_id not nullable.
ALTER TABLE Posts DROP COLUMN author_name, MODIFY author_id INT NOT NULL;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With