0

The following query works (example query below)

SELECT cat, dog, mouse, ids,
    (SELECT cheese
    FROM my_second_table AS a
    WHERE a.ids IN (1,2,3,4,5,6,7,8,9,10)
    LIMIT 1) AS cheese
FROM my_first_table

It gives me back the 5 columns with the correct data as I'd expect, including the cheese column.

The following query does not work, cheese column is always empty

SELECT cat, dog, mouse, ids,
    (SELECT cheese
    FROM my_second_table AS a
    WHERE a.ids IN (ids)
    LIMIT 1) AS cheese
FROM my_first_table

ids contains the same comma separated numbers as in the first query above, retrieved from each row in the my_first_table.

I feel this should work and that I am doing something wrong. Is it OK to use the SELECT results in a Sub-Select IN() clause?

superphonic
  • 7,954
  • 6
  • 30
  • 63

1 Answers1

2

Try with find_in_set function like

SELECT cat, dog, mouse, ids,
    (SELECT cheese
    FROM my_second_table AS a
    WHERE find_in_set(a.ids, ids)
    LIMIT 1) AS cheese
FROM my_first_table

IN accepts a list or parameters to search, FIND_IN_SET accepts a string parameter containing a comma-separated list.

In your case ids are comma separated string so find_in_set will true and IN clause return false

Sadikhasan
  • 18,365
  • 21
  • 80
  • 122