简体   繁体   中英

How to update two tables using id from one table to another?

I am writing a Node JS script, what I want to use for updating 2 tables from a remote database. The script does the following so far:

  • It connects to the remote database, selects the new values since a given time.
  • It connects to the local database, inserts or updates the new/edited rows to table A.
  • Updates or inserts new rows to the second table using id from table A as primary key. I've done task 1 and 2.

My code so far:

let mysql = require('mysql');

let con = mysql.createConnection({ //Server A
    host: "192.168.1.10",
    user: "user1",
    password: "pswd1",
    database: "a_database"
});

let con2 = mysql.createConnection({ //Server B
    host: "192.168.1.11",
    user: "user2",
    password: "pswd2",
    database: "b_database"
});

let sqlSelectDatabaseA = "SELECT uid,name,email,city,street,number FROM users \n" +
    "WHERE uid IN (SELECT DISTINCT u.uid FROM logs l INNER JOIN users u ON l.id = u.uid ORDER BY uid;";

let sqlSelectId = "SELECT max(id) AS ID FROM addresses";

let sqlInsertUsers = "INSERT INTO users (username,email,mobile,city,street,client_number,contactAddress) VALUES ? ON DUPLICATE KEY UPDATE \n" +
"username=VALUES(username),email=VALUES(email),mobile=VALUES(mobile),city=VALUES(city),street=VALUES(street);"; //I've solved the insert/update in this sql command
let sqlInsertAddresses = "INSERT INTO addresses (country,city,street,number) VALUES ?"; //Here I would need update too

con.connect(async function(err) {
    if (err) throw err;
    con.query(sqlSelectDatabaseA, function (err, result) {
        if (err) throw err;
        con2.connect(function(err) {
            if (err) throw err;
            con2.query(sqlSelectId, function (err, result2) {
                if (err) throw err;
                let addressId = result2[0].ID;
                let values1 = [];
                let values2 = [];
                for (let i = 0; i < result.length; i++) {
                    addressId++;
                    values1[i] = [result[i].city,result[i].street,result[i].number];
                    values2[i] = [result[i].name,result[i].email,result[i].city,result[i].street + ' ' + result[i].number,result[i].uid,++addressId];
                }
                con2.query(sqlInsertAddresses, [values1], function (err, result3) {
                    if (err)
                        throw err;
                    console.log("Number of records inserted/updated in addresses table : " + result3.affectedRows); //Now I only insert the addresses, don't check them if they exist, this would be the task, to achieve a check if it exists or not, if exists, update it, if not, insert it
                    con2.query(sqlInsertUsers, [values2], function (err, result4) {
                        if (err) throw err;
                        console.log("Number of records inserted/updated in users table: " + result4.affectedRows);
                        con.end();
                        con2.end();
                    });
                });

            });

        });
    });
});

I would like to find a solution for using the value at users.contactAddress as a PRIMARY KEY on the addresses table. If a record with the given primary key exists, it only updates the values, if doesn't, inserts a new record.

If it's possible, without new sql commands. But if there is no other way, that will do too.

Example:

  • in the logs table a new row appeared, it looks like |logId|userId|
  • the script uses this row's userId, connects to database A, gets the new values from the users table
  • using the values from database A the script inserts or updates the users table in database B
  • depending on if an update or an insert happened, it adds a row to addresses table, or updates the values in the addresses table where the id (PRIMARY KEY) equals to the updates users record's contactAddress field

Database structure

CREATE TABLE IF NOT EXISTS usersA (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `mobile` varchar(255) NOT NULL,
  `city` varchar(255) NOT NULL,
  `street` varchar(255) NOT NULL,
  `number` bigint(20) NOT NULL,
  PRIMARY KEY (`uid`)
);
CREATE TABLE IF NOT EXISTS logsA (
  `logId` int(11) NOT NULL AUTO_INCREMENT,
  `userId` varchar(255) NOT NULL,
  PRIMARY KEY (`logId`)
);
CREATE TABLE IF NOT EXISTS addressesB (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `city` varchar(255) NOT NULL,
  `street` varchar(255) NOT NULL,
  `buildingNumber` varchar(255) NOT NULL, 
  PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS usersB (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `mobile` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `city` varchar(255) NOT NULL,
  `street` varchar(255) NOT NULL,
  `klient_number` bigint(20) NOT NULL,
  `contactAddress` bigint(20) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `klient_number` (`klient_number`)
);
INSERT INTO usersA (username,email,mobile,city,street,number) VALUES("John Smith", "john.smith@gmail.com", "0000", "city", "street", 15);
INSERT INTO usersA (username,email,mobile,city,street,number) VALUES("Kate Smith", "kate.smith@gmail.com", "0000", "city_updated", "street1", 11);
INSERT INTO usersA (username,email,mobile,city,street,number) VALUES("Will Smith", "will.smith@gmail.com", "0000", "city2", "street2", 6);
INSERT INTO usersB (username,email,mobile,city,street,klient_number, contactAddress) VALUES("John Smith", "john.smith@gmail.com", "0000", "city", "street 15", 1, 1);
INSERT INTO usersB (username,email,mobile,city,street,klient_number, contactAddress) VALUES("Kate Smith", "kate.smith@gmail.com", "0000", "city 1", "street1 11", 2, 2);
INSERT INTO addressesB (city, street, buildingNumber) VALUES ("city", "street", "15");
INSERT INTO addressesB (city, street, buildingNumber) VALUES ("city 1", "street1", "11");
INSERT INTO logsA (userId) VALUES (2);
INSERT INTO logsA (userId) VALUES (3);

Desired result: the script selects users from usersA table, checks users in usersB table. If there is a record with the same klient_number as the PRIMARY KEY in usersA table (so, uid), then it updates, else it inserts. It does the same in addresses table.

Thank you for your help!

Perhaps you're after something like this:

INSERT INTO usersB 
(username
,mobile
,email
,city
,street
,klient_number) 
SELECT username
     , mobile
     , email
     , city
     , CONCAT_WS(' ',street,number)
     , uid 
  FROM usersA a 
    ON DUPLICATE KEY 
UPDATE username = a.username
     , mobile = a.mobile
     , email = a.email
     , city = a.city
     , street = CONCAT_WS(' ',a.street,a.number)
     , klient_number = a.uid;

Query OK, 3 rows affected, 1 warning (0.00 sec)
Records: 3  Duplicates: 1  Warnings: 0

SELECT * FROM usersB;
+----+------------+--------+----------------------+--------------+------------+---------------+----------------+
| id | username   | mobile | email                | city         | street     | klient_number | contactAddress |
+----+------------+--------+----------------------+--------------+------------+---------------+----------------+
|  1 | John Smith | 0000   | john.smith@gmail.com | city         | street 15  |             1 |              1 |
|  2 | Kate Smith | 0000   | kate.smith@gmail.com | city_updated | street1 11 |             2 |              2 |
|  3 | Will Smith | 0000   | will.smith@gmail.com | city2        | street2 6  |             3 |              0 |
+----+------------+--------+----------------------+--------------+------------+---------------+----------------+

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