Reputation: 413
Couldn't find exactly what I'm looking for anywhere else.
So I have table 1
users
----------
id
username
password
bio
isuser
email
and table 2
wp_users
----------
id
user_login
nice_username
password
email
There are 500 rows in 'wp_users' table. I would like to copy 'id' and 'user_login' into the users table ('id' and 'username') for each row.
How can I do this? MySQL isn't my strong point lol.
UPDATE: I have updated the tables above as I tried to simplify it but in return got the wrong solution.
Upvotes: 0
Views: 1704
Reputation: 967
You can use an INSERT
- SELECT
statement:
INSERT INTO `users` (id,username,password,bio,isuser,email) SELECT id,
user_login,null,null,null,null FROM `wp_users`;
You can put another fields or even static data on each field of the SELECT
part. I've put nulls just to illustrate.
Just remember that anything the SELECT
fetches will be inserted in the table the INSERT
statement says (so you can use clauses like WHERE
, GROUP BY
, HAVING
, etc on the SELECT
part).
Upvotes: 3
Reputation: 30651
I believe you are looking for a simple insert statement:
INSERT INTO users (id,username)
SELECT W.id,
W.user_login
FROM wp_users W
WHERE NOT EXISTS (SELECT NULL
FROM users U
WHERE U.ID = W.ID);
I am assuming the other columns in your users table are nullable, if not, you can add more columns to the select statement with the values in you'd like for the other columns.
You haven't mentioned any other keys or constraints, so I have assumed there aren't any.
I have also provided a check in the WHERE
clause to see if a row already exists for the same ID, so you only insert a row for each ID once.
Upvotes: 0