简体   繁体   中英

Is there a FIND_IN_SET by index in MySQL?

I know storing lists as strings is not wise, but I have to deal with that to export some data stored that way. I also know the FIND_IN_SET function, which returns the index of a certain string in a list:

SELECT FIND_IN_SET('bar', 'foo,bar,baz');
-- selects 2

Is there any built-in function (or combination of functions) to get the string in a particular index of the list? I'm looking for something like this:

SELECT IN_SET_AT_INDEX(2, 'foo,bar,baz');
-- selects 'bar'

I'd like to avoid a split-like function that makes the list a separate table, if possible.

SUBSTRING_INDEX() can do this, sort of:

mysql> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('foo,bar,baz', ',', 2), ',', -1) AS middle_one;
+------------+
| middle_one |
+------------+
| bar        |
+------------+

Yes, but it requires just a little trickery. The basis is substring_index() , but that gets everything up to the nth entry. Then I use reverse() twice and another substring_index() :

select reverse(substring_index(reverse(substring_index('foo,bar,baz', ',', 2)), ',', 1))

In your case, the transformations are:

original string:                'foo,bar,baz'
after substring_index(..., 2)   'foo,bar'
after inner reverse             'rab,oof'
after substring_index(..., 1)   'rab'
after outer reverse             'bar'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM