How to get relational table data name instead of id
P粉276064178
P粉276064178 2024-03-31 20:48:12
0
2
423

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粉276064178
P粉276064178

reply all(2)
P粉432906880

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粉521697419
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";
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template