I have two tables
hero
id | Name | universe_id |
---|---|---|
12 | mark | 1 |
99 | Gingpian | 1 |
universe
id | Name |
---|---|
1 | Andromeda |
2 | aurora |
How to use Universe name instead of universe_id to return hero
table data. Sorry, I don't have enough sql experience to accomplish this simple task. I read some answers in SO that require using 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 doesn't work.
renew:
The expected result is:
[{ id: 12, name: Mark, universe_id: Andromeda }, { id: 99, name: Glume, universe_id: Andromeda }]
P粉4329068802024-04-01 15:30:34
You can join universe
to hero
on the id
value and then intentionally select the initial SELECT# you want to see in the output ## Fields in clause:
SELECT `hero`.`id`, `hero`.`name`, `universe`.`name` FROM `hero` JOIN `universe` ON `hero`.`universe_id` = `universe`.`id`
P粉5216974192024-04-01 14:50:41
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";