简体   繁体   中英

MySQL: Multiple ids in one row from another table

This may be a bit convoluted but I'll give it a shot.

I have a table that has event data:

| id | event | from_location | to_location |
|  1 |  move |            12 |          14 |
|  2 |  move |            13 |          15 |

and the from location and to location are ids referenced in another able

| id | name    |
| 12 | london  |
| 13 | paris   |
| 14 | newyork |
| 15 | tokyo   |

My issue is I need to search both the first table based on the location, but using the name in the second, and I'd like to do it as simply as possible with one query.

If it was one column, I could just do a join and have the name available but since it is two, this doesn't work.

I could search for the name in the first table, then having the id, use that to search the other table - but I'd like to do it in one query.

So my question - is there a way to simply replace the ids with the corresponding name - then do the search, all in one query?

I would say one more thing - I didn't set this up. if I had, I'd have forgone the use of ids altogether and simply used the names as the keys. But now that it is how it is - lets assume I can't change this.

Thanks

If you want to check if the from or to location is a particular one:-

SELECT event_data.id, event_data.event, event_data.from_location, event_data.to_location 
FROM event_data
INNER JOIN locations l1 ON event_data.from_location = l1.id
INNER JOIN locations l2 ON event_data.to_location = l2.id
WHERE l1.name = 'somewhere'
OR l2.name = 'somewhere'

If you want a particular from location and another particular to location

SELECT event_data.id, event_data.event, event_data.from_location, event_data.to_location 
FROM event_data
INNER JOIN locations l1 ON event_data.from_location = l1.id
INNER JOIN locations l2 ON event_data.to_location = l2.id
WHERE l1.name = 'somewhere'
AND l2.name = 'somewhereelse'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM