How can I split comma separated value in MySQL int

2020-05-08 11:37发布

问题:

I have a function in MySQL that returns a list of integer values separated by a comma, thus forming a string.

e.g.

MyFunction(23);

Returns

----------------------
|  MyFunction(23)    |
|--------------------|
|  34,45,87,23,1     |
----------------------

This was a simple functionality required by the backend (Java) - but now, as new features are being suggested, I need these results for another query which might be iterating over these using IN keyword like the following:

SELECT id, myItemId, myItemValue, myDateTime 
FROM 
items where id 
IN (select MAX(id) from items where myItemId=1  
    and myItemValue 
    IN (select MyFunction(123)) 
group by myItemId);

Being a single csv element, the result of MyFunction(23) is not iterable. If I could use some function like Split(MyFunction(23)) which would generate results like the following will perfectly suit my queries without too much change.

Here're the results I expect:

-----------------------------
|  Split(MyFunction(23))    |
|---------------------------|
|  34                       |
|  45                       |
|  87                       |
|  23                       |
|  1                        |
-----------------------------

Another thing to take care is that MyFunction() might return empty result or a result with a single element (and no comma).

Is there an inbuilt function or a simple function I can create to get the same?

This is different than the other questions on stackoverflow as my requirement is very simple and derivations of other solutions will be an overkill. Looking something similar to split() function or a very simple implementation.

回答1:

You can use FIND_IN_SET function. For example:

SELECT FIND_IN_SET('34', '34,45,87,23,1'); -- return true

SELECT FIND_IN_SET('34', '34'); -- return true    

SELECT FIND_IN_SET('34', ''); -- return false

In your case, the SQL query will look like:

SELECT id,
       myItemId,
       myItemValue,
       myDateTime
FROM items
WHERE id IN
    (SELECT MAX(id)
     FROM items
     WHERE myItemId=1
       AND FIND_IN_SET(myItemValue, MyFunction(123))
     GROUP BY myItemId);