簡體   English   中英

如何使用 id 將兩個表從一張表更新到另一張表?

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

我正在編寫一個 Node JS 腳本,我想用它來更新遠程數據庫中的 2 個表。 到目前為止,該腳本執行以下操作:

  • 它連接到遠程數據庫,選擇自給定時間以來的新值。
  • 它連接到本地數據庫,將新的/編輯過的行插入或更新到表 A。
  • 使用表 A 中的 id 作為主鍵更新或插入新行到第二個表。 我已經完成了任務 1 和 2。

到目前為止我的代碼:

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();
                    });
                });

            });

        });
    });
});

我想找到一個解決方案,將 users.contactAddress 中的值用作地址表上的主鍵。 如果具有給定主鍵的記錄存在,則僅更新值,如果不存在,則插入新記錄。

如果可能,沒有新的 sql 命令。 但如果沒有其他辦法,那也行。

例子:

  • 在日志表中出現了一個新行,它看起來像 |logId|userId|
  • 該腳本使用該行的用戶 ID,連接到數據庫 A,從用戶表中獲取新值
  • 腳本使用數據庫 A 中的值插入或更新數據庫 B 中的用戶表
  • 根據是否發生更新或插入,它向地址表添加一行,或更新地址表中的值,其中 id (PRIMARY KEY) 等於更新用戶記錄的 contactAddress 字段

數據庫結構

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);

預期結果:腳本從 usersA 表中選擇用戶,檢查 usersB 表中的用戶。 如果在 usersA 表中存在與 PRIMARY KEY 具有相同 klient_number 的記錄(因此,uid),則它會更新,否則它會插入。 它在地址表中做同樣的事情。

感謝您的幫助!

也許你在追求這樣的事情:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM