'How to get relation table data name instead of id
I have two tables
Hero
| id | name | universe_id |
|---|---|---|
| 12 | Mark | 1 |
| 99 | Glume | 1 |
Universe
| id | name |
|---|---|
| 1 | Andromeda |
| 2 | Aurora |
How to return hero table data with universe name instead of universe_id. I'm sorry, I don't have enough experience in sql for this simple task. I read some answers in SO that need to use JOIN.
I try to do something like this.
exports.getHero = (req, res) => {
const sql = "SELECT * FROM `hero` WHERE `id`='" + req.params.id + "' JOIN `universe` WHERE `id`=`universe_id` ON `hero.universe_id`=`universe.id`";
db.query(sql, (error, results) => {
if (error) {
console.log(error);
} else {
response.returnSingleValue(results, res);
}
});
};
But this is won't work.
UPD:
Expected result to be:
[{
id: 12,
name: Mark,
universe_id: Andromeda
},
{
id: 99,
name: Glume,
universe_id: Andromeda
}]
Solution 1:[1]
const sql = "SELECT h.id, h.name, u.name as universe_id FROM `hero` as h LEFT JOIN `universe` as u ON h.universe_id=u.id";
Solution 2:[2]
You can JOIN universe to hero on the id value, then deliberately choose the fields in your initial SELECT clause which you want to see in your output:
SELECT `hero`.`id`, `hero`.`name`, `universe`.`name`
FROM `hero`
JOIN `universe` ON `hero`.`universe_id` = `universe`.`id`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vanesicks |
| Solution 2 |
