简体   繁体   English

如何使用 id 将两个表从一张表更新到另一张表?

[英]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.我正在编写一个 Node JS 脚本,我想用它来更新远程数据库中的 2 个表。 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.它连接到本地数据库,将新的/编辑过的行插入或更新到表 A。
  • Updates or inserts new rows to the second table using id from table A as primary key.使用表 A 中的 id 作为主键更新或插入新行到第二个表。 I've done task 1 and 2.我已经完成了任务 1 和 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.我想找到一个解决方案,将 users.contactAddress 中的值用作地址表上的主键。 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.如果可能,没有新的 sql 命令。 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|在日志表中出现了一个新行,它看起来像 |logId|userId|
  • the script uses this row's userId, connects to database A, gets the new values from the users table该脚本使用该行的用户 ID,连接到数据库 A,从用户表中获取新值
  • using the values from database A the script inserts or updates the users table in database B脚本使用数据库 A 中的值插入或更新数据库 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根据是否发生更新或插入,它向地址表添加一行,或更新地址表中的值,其中 id (PRIMARY KEY) 等于更新用户记录的 contactAddress 字段

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.预期结果:脚本从 usersA 表中选择用户,检查 usersB 表中的用户。 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.如果在 usersA 表中存在与 PRIMARY KEY 具有相同 klient_number 的记录(因此,uid),则它会更新,否则它会插入。 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 |
+----+------------+--------+----------------------+--------------+------------+---------------+----------------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在一个中连接两个表,在另一个表中有一个id和多个id - join two tables in one with one id and multiple ids in another table 如何在一个查询中根据另一个表中的 id 计算两个不同表中的值? - How do I count values from two different tables based off a id from another table in one query? 仅当ID在2个表而不是第3个表上匹配时,才将列从一个表更新到另一个表 - Update column from one table to another only if the id matches on 2 tables and not the third 仅当使用MySQL在一个表中的列值与另一表相同时,才如何从两个表返回数据? - How to return data from two tables only when the column value in one table is same as another table using MySQL? 如何连接3个表,其中一个表映射其他两个表的ID? - How to joint 3 table where one table map id from the two other tables? 如何更新查询两个表并在一个表中更新? - How do I update query two tables and update in one table? 尝试通过使用另一个表中的id值将两个表连接在一起 - Trying to connect two tables together by using id value from one table on the other 从一张表中选择用户 ID 并在另一张表中更新 - Select User id from one table and update in another table 如何从另一个表更新一个表? - How to update one table from another table? 如何使用另一个表中的数据更新sql中的表? - How to update a table in sql using data from another one?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM