Creating a MySQL SET's from a string

纵然是瞬间 提交于 2019-12-20 01:08:12

问题


Is there a way to create a set from a string of separated values in MySQL? For example:

'the,quick,brown,fox' => 'the','quick','brown','fox'

A sort of inverse EXPORT_SET without the bit fiddeling.

Regards


回答1:


If you're trying to use the set in an IN statement, instead of splitting the string, you could do a comparison like:

SELECT * FROM `table` WHERE 'the,quick,brown,fox' REGEXP CONCAT('(^|,)','word','(,|$)');

I'm not sure how efficient this would be if your dataset is large, but it might be faster than reading into and selecting from a temporary table.




回答2:


Tested on MySQL 5.1.41:

DROP TABLE IF EXISTS n;
CREATE TEMPORARY TABLE n AS
  SELECT -1 AS N UNION
  SELECT -2 UNION
  SELECT -3 UNION
  SELECT -4 UNION
  SELECT -5;

DROP TABLE IF EXISTS foo;
CREATE TABLE foo AS
  SELECT 'the,quick,brown,fox' AS csv;

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(foo.csv, ',', n.n), ',', 1) AS word
FROM foo JOIN n
  ON (LENGTH(REPLACE(foo.csv, ',', ''))-LENGTH(foo.csv) <= n.n+1);

Result:

+-------+
| word  |
+-------+
| fox   |
| brown |
| quick |
| the   |
+-------+



回答3:


You could split the text into separate elements, read into a temp table, and then select the result.

e.g.

http://forums.mysql.com/read.php?60,78776,242420#msg-242420




回答4:


Wouldn't FIND_IN_SET solve your problem ?

FIND_IN_SET()



来源:https://stackoverflow.com/questions/1858822/creating-a-mysql-sets-from-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!