我正在尝试使用 Node、Express 和 JavaScript 在一条路线上显示来自两个数据库表的数据。我已使用 knex 将我的 Express 应用程序连接到数据库,并尝试使用 MySQL SELECT 查询从两个表中获取数据以显示在服务器上。
“offence_columns”表中“column”属性/列中的数据显示为“offences”表中的一列,因此我有两个 promise ,其中一个从中的“column”属性中获取数据'offence_columns' 表,另一个在其中选择 'offences' 表中的 'area' 属性和从 'columns' 属性中选择的另一个属性/列。
由于“column”是 MySQL 中的保留字,我在选择它时遇到了一些问题。在提供的代码中使用单引号为我提供了终端中的代码:
Unhandled rejection Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as
0
fromoffences
' at line 1.
如果我用单引号代替反引号 (column
),我会得到同样的错误,但如果我尝试同时使用这两个 ('column
'),我会得到不同的结果错误:
Error: ER_BAD_FIELD_ERROR: Unknown column '
column
' in 'field list'.
我试过使用别名,但似乎没有帮助。
router.get('/api/search/:offence', function(req, res, next) {
req.db.from('offence_columns').select('column').where('pretty',"=",req.params.offence)
.then((rows) => {
req.db.from('offences').select('area', rows)
.then((rows2) => {
res.json({"Error" : false, "Message" : "Success", "City" : rows2})
})
})
.catch((err) => {
console.log(err);
res.json({"Error" : true, "Message" : "Error in MySQL query"})
})
});
最佳答案
首先,考虑调整您的架构。 column
对于数据库列来说是一个非常糟糕的名称...正如您已经发现的那样,它会导致各种困惑!
但是,Knex 通常在其输出中用反引号将名称括起来,这应该可以避免保留字问题。这实际上不是你的问题。您看到的是尝试使用其中的数组发出查询的结果:
req.db.from('offences').select('area', rows)
这里,rows
是一个数组,可以为空也可以不为空。这是之前查询的结果。
我怀疑您正在寻找的是更多类似的东西(猜测,因为我不知道您的模式是什么):
db.from("offence_columns")
.select("column")
.where("pretty", "=", req.params.offence)
.then(rows => {
if (rows.length === 0) {
res.json({ error: false, message: "No cities matched." });
}
req.db
.from("offences")
// This assumes that `offence_columns` has an `area` column
.where("area", "=", rows[0].area)
.then(areas => {
res.json({ Error: false, Message: "Success", city: areas[0] });
});
});
这里还有很多问题。一方面,如果任一查询可以返回多个结果怎么办?此外,一开始加入可能会更好:
db
.select('city')
.from('offence_columns')
.join('offences', 'offence_columns.area', '=', 'offences.area')
.where('pretty', '=', req.params.offence)
但是,如果不知道您的架构是什么样子,这一切都是猜测。
关于javascript - 如何修复 router.get 中相互依赖的两个 Knex MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56405261/