在MySQL中快速将逗号分隔的字符串转换为列表

时间:2017-08-01 22:42:58

标签: mysql csv

我有一个看起来像这样的mySQL表:

>> customer_table

customerId  | list1   |  list2    | list3
--------------------------------------------
     0      | 0,1,2,3 | 3,2,443,3| 3,55,3,4
--------------------------------------------
     1      | 5,1,8,9 | 5,2,41,6 | 1,5,3,90

列customerId是一个int主键。其余字段是存储在mediumtext字段中的逗号分隔字符串列表(因此list1为'0,1,2,3'等)。每个中等文本字段长度大约为500,000个字符(其中有近120,000个字符),因此非常大。

我想查询此表,以便我可以快速将列表转换为数字,然后获取该解析列表的第i个元素并返回它们。我一般会一次查询一行customer_table,但如果过程很快,有时可能更多。伪代码(写得不好)看起来像这样

>> select csv_parsed(list1) # need to search a parsed version of the list
from customer_table 
where customerId = 0 
and index = 0 or index = 1 or index = 4 # These are the ith elements of the parsed list

应该返回以下内容:

>> customerId | 0  | 1 | 4 
   -----------------------
       0      | 0  | 1 | 3

1 个答案:

答案 0 :(得分:1)

SQL不支持具有动态选择列表的查询。选择列表中的列在准备查询时是固定的,执行期间发现的数据无法扩展或重命名选择列表中的列。

您可能想看看SUBSTRING_INDEX()。这是MySQL中的内置函数,可以选择由你想要的字符分隔的子字符串。

select customerId, 
  substring_index(substring_index(list1, ',', 1), ',', -1) AS 0,
  substring_index(substring_index(list1, ',', 2), ',', -1) AS 1,
  substring_index(substring_index(list1, ',', 4), ',', -1) AS 4,
from customer_table 
where customerId = 0 

如果您想使用列表中的单个元素,请不要将数据存储在以逗号分隔的字符串中。

相关问题