我在下面的代码中使用'nestTables'选项将SQL查询返回的数据分成各自的表。我还在我的查询中包含了一个计算字段,我希望将其包含在主表中。
举个例子,我正在执行以下路线:
knife cookbook upload ${PWD##*/} -o ..
我收到以下JSON响应:
router.route('/person/:personId').get(function(req,res){
var person_id = req.params.personId;
db.getConnection(function(err, connection) {
if (err) {
return res.status(503).send({ result: false, error: 'CONNECTION error: ' + err.code});
} else {
var sqlString='SELECT *, someField - 1 as calculated FROM person LEFT JOIN person_status ON person.id = person_status.person_id WHERE person.id = ' + person_id;
var options={sql:sqlString,nestTables:true};
connection.query(options, function(error, rows, fields) {
connection.release();
var nestingOptions = [
{tableName: 'person', pkey:'id'},
{tableName: 'person_status', pkey:'id', fkeys:[{table:'person',col:'person_id'}]}
];
if (error) {
return res.status(500).send({ result: false, error: 'QUERY ERROR: ' + error.code});
} else {
return res.status(200).send(rows);
}
});
}
});
});
理想情况下,我想将计算字段包含在person子组中,如下所示:
[
{
"person": {
"id": 1,
other person data . . .
"person_status": [
{
"id": 3,
other data . . .
}
]
},
"person_status": {
"id": 3,
other data . . .
},
"": {
"calculated": 0
}
}
]
有什么方法可以将计算字段包含在人员表中,还是有更好的解决方案可以解决这个问题?
提前致谢!
答案 0 :(得分:1)
我看到两种方法可以解决这个问题,一种是使用SQL的脏方法:
var sqlString = 'SELECT *, someField - 1 as calculated FROM person WHERE person.id=?';
sqlString = 'SELECT * FROM (' + sqlString + ') as person';
sqlString += ' LEFT JOIN person_status ON person.id = person_status.person_id';
var options={sql:sqlString, nestTables:true};
connection.query(options, [person_id], function(error, rows, fields) {
使用js的明显解决方案:
var sqlString = 'SELECT *, someField - 1 as calculated FROM person LEFT JOIN person_status ON person.id = person_status.person_id WHERE person.id=?';
var options = {sql:sqlString, nestTables:true};
connection.query(options, [person_id], function(error, rows, fields) {
rows.forEach(function(row) {
row.person.calculated = row[''].calculated;
delete row[''];
});
我认为没有更愉快的解决方案。我甚至检查了是否有可能欺骗FieldPacket或RowDataPacket解析器,但没有看到伪造表名的方法(没有猴子修补mysql驱动程序)。