简体   繁体   English

如何从逗号分隔的字符串中获取find_in_set的记录。[MySql]

[英]How to get record where find_in_set from a comma saperate string.[MySql]

I have a comma separate string like "1,2,3" and a column in table is also contain comma separate value like "1,2,4,5,3" how to get all records that match any value to any value. 我有一个逗号分隔的字符串,例如“ 1,2,3”,并且表中的一列还包含逗号分隔的值,例如“ 1,2,4,5,3”,该如何获取将任何值匹配到任何值的所有记录。

for example 例如

  • id---category ID ---类别
  • 1---1,2,4,5 1 --- 1,2,4,5
  • 2---1,2,3,6 2 --- 1,2,3,6
  • 3---2,3,5 3 --- 2,3,5

If I search for string "1,2,3" then I should get record the category contains 1 or 2 or 3 or 1,2 or 1,3 or 2,3 or 1,2,3. 如果我搜索字符串“ 1,2,3”,则应该获取该类别包含1或2或3或1,2或1,3或2,3或1,2,3的记录。 It should not return the duplicate value where as we can group them. 它不应返回重复的值,因为我们可以将它们分组。

Is it possible to get all record with a single query. 是否可以通过单个查询获取所有记录。

尝试这个:

select * from table where category IN (1,2,3);

You should not be storing lists of ids in strings. 您不应该在字符串中存储ID列表。 Here are reasons why: 原因如下:

  • Values should be stored using the correct type. 值应使用正确的类型存储。 int <> string. int <>字符串。
  • SQL has lousy string processing functions. SQL具有糟糕的字符串处理功能。
  • Foreign keys should be properly declared. 外键应正确声明。
  • SQL will not be able to optimize these queries. SQL将无法优化这些查询。
  • SQL has a great way to store lists. SQL有一种存储列表的好方法。 It is called a table not a string . 它称为而不是字符串

But, sometimes you are stuck with someone else really, really, really, really, really bad data modeling decisions. 但是,有时您会被其他非常,非常,非常非常糟糕的数据建模决策所困扰。 You can do something, using regular expressions: 您可以使用正则表达式执行某些操作:

where category regexp replace($string, ',', '|')

or perhaps more accurately: 或更准确地说:

where concat(',', category, ',') regexp concat(',', replace($string, ',', ',|,'), ',')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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