[英]How to use an HTTP request to add varchar values to a MySQL query in NodeJS
[英]How to use passed array in nodejs mysql query to compare with specified values?
所以我试图弄清楚如何插入具有相同“ID”的多个相同行,但前提是“DATE”值与具有相同“ID”的其他行不同。 我希望这是有道理的。
我当前插入数据的查询是这样的。
query(`
INSERT INTO table (id, otherdata, somedata, otherdata, etc, date)
VALUES ?
`, [data])
数据值看起来像这样
[
['id1', 'otherdata1', 'somedata1', 'otherdata1', 'etc1', 'date1'],
['id2', 'otherdata2', 'somedata2', 'otherdata2', 'etc2', 'date2'],
['id3', 'otherdata3', 'somedata3', 'otherdata3', 'etc3', 'date3'],
['id3', 'otherdata3', 'somedata3', 'otherdata3', 'etc3', 'date3'], <- this would be ignored, as id3 and date3 matches with row 3 in this or if such data would exist in database it would do the same.
['id3', 'otherdata3', 'somedata3', 'otherdata3', 'etc3', 'someotherDate'], <- this would go through as DATE is different than row3 and only ID matches
['id4', 'otherdata4', 'somedata4', 'otherdata4', 'etc4', 'date4'],
]
呃,好吧。 我放弃了在 1 个查询中执行此操作。 我把它变成了 2。这是一种非常“丑陋”的方式,但会在不知道任何其他解决方法的情况下使用它。
如果有人有类似的问题,我是这样解决的。
id 必须是数组中的第一个,日期是最后一个。 数组格式应该像我在顶部的帖子中指定的那样。
query(`SELECT id,DATE_FORMAT(date,\'%Y-%m-%d %H:%i:%s\') AS date FROM table WHERE (id) IN(?)`, [data.map(a => a[0])])
.then(res => {
data = data.filter(arr => {
// filter out that already has same id with same date
if ( !res.some(r => r.id == arr[0] && r.date == arr[arr.length-1]) )
return arr;
})
// if it's empty, return
if (data.length == 0)
return console.log("success")
query("INSERT INTO table (id, ...extra.data.here, date) VALUES ?;", [data])
.then(() => {
console.log("success")
})
.catch((error) => {
console.error(error);
});
})
.catch(err => console.error(err))
你可以试试这个。 所以你需要将数组传递给 VALUES 子句
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customers (name, address) VALUES ?";
var values = [
['John', 'Highway 71'],
['Peter', 'Lowstreet 4'],
['Amy', 'Apple st 652'],
['Hannah', 'Mountain 21'],
['Michael', 'Valley 345'],
['Sandy', 'Ocean blvd 2'],
['Betty', 'Green Grass 1'],
['Richard', 'Sky st 331'],
['Susan', 'One way 98'],
['Vicky', 'Yellow Garden 2'],
['Ben', 'Park Lane 38'],
['William', 'Central st 954'],
['Chuck', 'Main Road 989'],
['Viola', 'Sideway 1633']
];
con.query(sql, [values], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
});
我相信你想要实现的是一个 upsert。 您需要首先在数据库中定义主键/唯一键,例如id
然后运行以下查询:
INSERT IGNORE INTO books
(id, otherdata, somedata, otherdata, etc, date)
VALUES
(data);
您可以阅读有关IGNORE 语句的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.