简体   繁体   中英

mysql join get column value from comma separated value

I have two tables as below :

vehicles :

vehicle_id   number_plate
1            B 101 RA
2            B 501 JU
3            B 401 JA
4            B 201 RU

team :

team_id      team_name    available_vehicles
1            A-001        1,2
2            A-002        NULL
3            A-003        4

I want to get value where the position of vehicle in the team table, my desired output would look like this:

vehicle_id ║ number_plate ║ team_name
1          ║ B 101 RA     ║ A-001
2          ║ B 501 JU     ║ A-001
3          ║ B 401 JA     ║ NULL
4          ║ B 201 RU     ║ A-003

You can use find_in_set-function, but that would be quite inefficient for larger datasets.

select v.vehicle_id, v.number_plate, t.team_name
from vehicles v
  join team t on find_in_set(v.vehicle_id, t.available_vehicles);

You should consider creating proper database structure with a separate table for

create table team_vehicles (
team_id int, 
vehicle_id int,
primary key(team_id, vehicle_id)
)

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