Pages

Showing posts with label MySql. Show all posts
Showing posts with label MySql. Show all posts

Thursday, March 13, 2014

MySQL: Split comma separated list into multiple rows

    In MySQL this can be achieved as below  
 
    SELECT id, length FROM vehicles WHERE id IN ( 117, 148, 126)

    +---------------+
    | id  | length  |
    +---------------+
    | 117 | 25        |
    | 126 | 8        |
    | 148 | 10        |
    +---------------+

    SELECT id,vehicle_ids FROM load_plan_configs WHERE load_plan_configs.id =42

    +---------------------+
    | id  | vehicle_ids   |
    +---------------------+
    | 42  | 117, 148, 126 |
    +---------------------+

    Now to get the length of comma separated vehicle_ids use below query

    Output

    SELECT length FROM vehicles, load_plan_configs   WHERE load_plan_configs.id = 42 AND FIND_IN_SET(vehicles.id, load_plan_configs.vehicle_ids)
   
    +---------+
    | length  |
    +---------+
    | 25        |
    | 8          |
    | 10       |
    +---------+