[英]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: 我也知道
FIND_IN_SET
函数,它返回列表中某个字符串的索引:
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: SUBSTRING_INDEX()
可以做到这一点,有点:
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. 基础是
substring_index()
,但是它可以获得第n个条目的所有内容。 Then I use reverse()
twice and another substring_index()
: 然后我使用
reverse()
两次和另一个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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.