SteadH
SteadH

Reputation: 113

MySQL - Return Multiple Rows based on IN ()

Working with MySQL, I've got two tables - one with videos, the other with products. Each row in the products table has a column called productVideoOrder, which is a comma separated list of videoIDs (relating to the video table) in the order that the user has placed them.

What I describe below would be easier if the relationship was in an intermediate table, but for other functions of this project, the comma separated list made sense.

I'm trying to get a table that returns column one: videoTitle, column two: productName. Is there a way to left join based on a comma separated list? I would like the results table to allow repeated rows, for example, if two product lists video one in the productVideoOrder, this table would have two rows for that video, one listing product one, the other listing product two.

I can clarify anything needed. Thanks in advance!

Upvotes: 1

Views: 214

Answers (1)

Quassnoi
Quassnoi

Reputation: 425341

SELECT  p.name, v.title
FROM    product p
LEFT JOIN
        video v
ON      FIND_IN_SET(v.id, p.productVideoOrder)

This is not going to be fast.

If you have some reasonable limit on the number of videos which can be assigned to a product, you may try using this:

SELECT  p.name, v.title
FROM    product p
CROSS JOIN
        (
        SELECT  1 AS n
        UNION ALL
        SELECT  2 AS n
        UNION ALL
        SELECT  3 AS n -- add more if needed
        )
LEFT JOIN
        video v
ON      v.id = SUBSTRING_INDEX(SUBSTRING_INDEX(productVideoOrder, ',', n), ',', -1)
        AND SUBSTRING_INDEX(SUBSTRING_INDEX(productVideoOrder, ',', n), ',', -1) <> SUBSTRING_INDEX(SUBSTRING_INDEX(productVideoOrder, ',', n - 1), ',', -1)

This will be using an index on v.id.

Upvotes: 0

Related Questions