gpt4 book ai didi

mysql - 我如何从 sql 中的 select 语句返回字符串字段

转载 作者:行者123 更新时间:2023-11-29 18:58:09 28 4
gpt4 key购买 nike

这是问题的架构:

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
}
]

最佳答案

修改您的查询语句以包含 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";

关于mysql - 我如何从 sql 中的 select 语句返回字符串字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44033009/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com