这是问题的架构:
CREATE TABLE organization (
id INT AUTO_INCREMENT PRIMARY KEY,
org_name VARCHAR(255) UNIQUE NOT NULL,
parent_id INT
);
ALTER TABLE organization
ADD CONSTRAINT FOREIGN KEY (parent_id)
REFERENCES organization(id);
我想在查询选择中返回一个字符串字段..例如,当我检索所有数据时,我希望它具有relationship_type:但是,我的架构中没有relationship_type字段; 比如这样的东西:
[{
"relationship_type": "parent",
"org_name": "Banana tree"
}, {
"relationship_type": "parent",
"org_name": "Big banana tree"
}, {
"relationship_type": "sister",
"org_name": "Brown Banana"
}, {
"relationship_type": "sister",
"org_name": "Green Banana"
}, {
"relationship_type": "daughter",
"org_name": "Phoneutria Spider"
}, {
"relationship_type": "sister",
"org_name": "Yellow Banana"
}]
来自此代码:
app.get("/api/listAll/all/:id", function(req, res){
var daughtersQuery = "select * from organization where parent_id = " + req.params.id;
var parentQuery = "select * from organization where id = (select parent_id from organization where id = " + req.params.id + ")";
var sistersQuery = "select * from organization where parent_id = (select parent_id from organization where id = " + req.params.id + ") && id != " + req.params.id;
var q = "select distinct id, org_name, parent_id from (" +
daughtersQuery + " union all " +
parentQuery + " union all " +
sistersQuery + " ) a order by org_name asc";
// console.log(q);
connection.query(q, function (error, results) {
if (error) throw error;
// console.log(results);
res.send(results);
});
// var page_no = req.query.page;
// console.log(page_no);
});
app.listen(8080, function() {
console.log("Server Running");
});
我目前正在检索此.. null是根(父):
[
{
"id": 1,
"org_name": "black banana",
"parent_id": null
},
{
"id": 3,
"org_name": "green banana",
"parent_id": 2
}
]
答案 0 :(得分:0)
修改您的查询语句以包含relationship_type
字段:
var daughtersQuery = "select *, 'daughter' as relationship_type from organization where parent_id = " + req.params.id;
var parentQuery = "select *, 'parent' as relationship_type from organization where id = (select parent_id from organization where id = " + req.params.id + ")";
var sistersQuery = "select *, 'sister' as relationship_type from organization where parent_id = (select parent_id from organization where id = " + req.params.id + ") && id != " + req.params.id;
var q = "select distinct id, relationship_type, org_name, parent_id from (" +
daughtersQuery + " union all " +
parentQuery + " union all " +
sistersQuery + " ) a order by org_name asc";