My db is:
# item_rel
id | item_ids
--------------------------
1 | 1,2,4,6,8,10
2 | 3,5,7
3 | 9,11,12
.. | ............
# items
id | name
--------------------------
1 | Lorem
2 | Ipsum
3 | Sed
4 | Amed
.. | ............
The problem is select items with one query. I have tried many way but no luck. Only this one approachs the expected result:
SELECT
items.*
FROM
items
WHERE
items.id IN (
SELECT
items_rel.ids
FROM
items_rel
WHERE
items_rel.ids LIKE "1" OR
items_rel.ids LIKE "1,%" OR
items_rel.ids LIKE "%,1" OR
items_rel.ids LIKE "%,1,%"
)
This query returns only one item.. How to get every item with one query?
This was a bit tricky, but was so not imposible, nor a sign of ignorance:
SET @ids = (SELECT ids FROM item_rel
WHERE ids LIKE '1' OR ids LIKE '1,%' OR ids LIKE '%,1' OR ids LIKE '%,1,%') ;
SET @ids = (SELECT IF (@ids IS NOT NULL,@ids,'99999999999999999999999')) ;
SET @q = CONCAT('SELECT * FROM items WHERE ID IN (', @ids,')') ;
PREPARE stmt FROM @q ;
EXECUTE stmt ;
"99999999999999999999999" must be any value that never found in your db.