sqlmysqlrecursive-queryfind-in-set

FIND_IN_SET - Getting partial output due to doubled values


Table "skus":

plant_species_ids
1,2,3,2,3,1

Table "plant_species"

id name
1 Plant 1
2 Plant 2
3 Plant 3

The relevant part of my MySQL code:

...
GROUP_CONCAT(plant_species.name SEPARATOR ', ') as plant_species_names
...
LEFT JOIN plant_species 
       ON FIND_IN_SET(plant_species.id, skus.plant_species_ids) > 0

Output I get:

Plant 1,Plant 2,Plant 3

Result I need to get:

Plant 1,Plant 2,Plant 3, Plant 2,Plant 3,Plant 1

From what I can tell it's acting like I'm using DISTINCT when I'm not.

Any ideas how to do this?


Edit

Here is my final code for anyone else that has this same problem: ``

SELECT orders.id, orders.customer_id, orders.invoice_amount, orders.delivery_date, orders.delivery_time, GROUP_CONCAT(skus.name SEPARATOR ', ') as sku_name, orders.sku_ids as sku_ids, orders.sku_weights as sku_weights

FROM orders

JOIN json_table(concat('[',orders.sku_ids,']'), '$[*]' columns (id int path '$')) AS species_ids

LEFT JOIN skus on skus.id=species_ids.id
WHERE orders.id=10
GROUP BY orders.id;

``


Solution

  • A simpler way is to wrap your ids column in brackets and expand it using json_table, but I'm not sure how to do that as a left join.

    select skus.id, GROUP_CONCAT(plant_species.name SEPARATOR ', ') as plant_species_names
    from skus
    join json_table(concat('[',skus.plant_species_ids,']'), '$[*]' columns (id int path '$')) as species_ids
    left join plant_species on plant_species.id=species_ids.id
    group by skus.id
    

    fiddle

    The original select doesn't find the later duplicate ids because the join is only comparing skus rows to plant_species rows, not the individual ids in plant_species_ids, and find_in_set will find only the first instance of a plant_species id in plant_species_ids.