简体   繁体   English

一个MySQL查询可能吗? “列包含任何数组的值”

[英]Possible with one MySQL query? “column contains any of the array's values”

Basically I want to check whether a mysql text column, which contains comma-separated values, contains any of the values contained in an array. 基本上我想检查包含逗号分隔值的mysql文本列是否包含数组中包含的任何值。 I know this can be done with a loop and multiple queries, but I was hoping for a single query. 我知道这可以通过循环和多个查询来完成,但我希望能够进行单个查询。 Is this possible? 这可能吗? Thank you. 谢谢。

I would use a solution like this: 我会使用这样的解决方案:

SELECT
  *
FROM
  yourtable
WHERE
  str RLIKE
  CONCAT('[[:<:]]', REPLACE('values,in,the,array', ',', '[[:>:]]|[[:<:]]'), '[[:>:]]')

this will make the following string: 这将生成以下字符串:

'values,in,the,array'

like this: 像这样:

[[:<:]]values[[:>:]]|[[:<:]]in[[:>:]]|[[:<:]]the[[:>:]]|[[:<:]]array[[:>:]]

[[:<:]] and [[:>:]] are word boundaries so it will match only whole words, and | [[:<:]][[:>:]]是单词边界,因此它只匹配整个单词和| is an OR so it will match any of the words. 是一个OR,因此它将匹配任何单词。 Please see fiddle here . 请看这里的小提琴。

SELECT COUNT(*) FROM my_table WHERE (my_column LIKE '%,0,%' OR my_column LIKE '%,1,%');

要么

SELECT COUNT(*) FROM my_table WHERE (my_column REGEXP LIKE '.*,[0-1],.*');

Do you mean 你的意思是

... WHERE my_column LIKE '%first_array_value%' OR my_column LIKE '%second_array_value%'

It will work but very bad because of performance. 由于性能的原因,它会起作用但非常糟糕。 There is also another way 还有另一种方式

... WHERE MATCH (my_column) AGAINST ('first_array_value second_array_value')

but the best way is to change data structure if possible. 但最好的方法是尽可能改变数据结构。

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

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