Ahmad Fauzi
Ahmad Fauzi

Reputation: 43

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

Upvotes: 0

Views: 57

Answers (1)

slaakso
slaakso

Reputation: 9050

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)
)

Upvotes: 2

Related Questions