简体   繁体   中英

Mysql different tables, copy over, match field, but column rows are random

I have two different tables table_usernames and jos_users, I need to match the fields username and users from both tables columns and then if the column row matches i need table-usernames (registered date) column to copy over to the jos-users (registration) column row field. So far the closest thing I have found is

update
  table1 t1
  join table2 t2 on t2.field = t1.field
set
  t1.field1 = t2.matchingfield
where
  t1.whatever = t2.whatever

but that does not look like it would work in the situation I have, just wanted to verify before i destroy my database and find my backup is corrupt... Thank you in advance

As per your requirement you are having two tables table_usernames and jos_users.

Now First of all i have to find mapping of this two table that you already define username from table_usernames and users from jos_users.

Now you want to set the ragistered date of table_usernames to registration field of jos_users.

UPDATE table_usernames t1,
           jos_users t2
    SET t2.registration = t1.registered_date // assign registered_date value to registration column of jos_users table 
    WHERE (t1.username = t2.users);   // Mapping (Common) Columns of both tables

This will update registration coulmn of jos_users table from table_usernames table.

From your description the statement would be

UPDATE table_usernames t1
INNER JOIN jos_users t2 ON t1.username = t2.users
SET t2.registration = t1.registered_date;

The inner join works already as a filter for matching user names. For a visual explanation of joins visit this link .

If you want to check first, if your statement is correct, either you transform it to a select first, so you can see, which records will be updated

SELECT * FROM 
table_usernames t1
INNER JOIN jos_users t2 ON t1.username = t2.users;

or, if you are using a storage engine that supports transactions for all tables, like InnoDB, you can do this:

START TRANSACTION;
UPDATE table_usernames t1
INNER JOIN jos_users t2 ON t1.username = t2.users
SET t2.registration = t1.registered_date;

Then you can check with SELECT whatever... (in the same session!) if everything went fine. The data will be written when you do

COMMIT;

if you don't want it to be written, you do

ROLLBACK;

Check if your table are using InnoDB as storage engine with

SHOW CREATE TABLE your_table_name\G

and see in the last line

) ENGINE = InnoDB ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM