mysql - 在 MySql 正则表达式查询中使用变量

标签 mysql regex

我正在尝试在多个列中搜索标签并返回类型。

下面是我的查询的简化版本。

set @item_1 = '(Tag1|Tag2|Tag3|Tag4)(,| |$)',
    @item_2 = '(Tag5|Tag6|Tag7|Tag8)(,| |$)';
select
  case
    when tags_1 regexp @item_1
      then 'Item_1'
    when tags_2 regexp @item_1
      then 'Item_1'
    when tags_1 regexp @item_2
      then 'Item_2'
    when tags_2 regexp @item_2
      then 'Item_2'
    else 'Uncategorised'
  end type
from my_table
order by date desc

有什么方法可以将标签设置为变量并在正则表达式中使用它们。我已经尝试了上述方法,但收到以下错误。

[ERROR in query 2] Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation 'regexp'

谢谢。

最佳答案

在每个 REGEXP 表达式之后添加 COLLATE

set @item_1 = 'Tag1|Tag2|Tag3|Tag4',
    @item_2 = 'Tag5|Tag6|Tag7|Tag8';
select
  case
    when tags_1 regexp concat(@item_1, '(%)(,|$)') COLLATE utf8_unicode_ci
      then 'Item_1'
    when tags_2 regexp concat(@item_1, '(%)(,|$)') COLLATE utf8_unicode_ci
      then 'Item_1'
    when tags_1 regexp concat(@item_2, '(%)(,|$)') COLLATE utf8_unicode_ci
      then 'Item_2'
    when tags_2 regexp concat(@item_2, '(%)(,|$)') COLLATE utf8_unicode_ci
      then 'Item_2'
    else 'Uncategorised'
  end type
from my_table
order by date desc;

另一个解决方法是将表格排序规则更改为 latin1 - 默认排序规则/架构默认。您不再需要指定COLLATE

关于mysql - 在 MySql 正则表达式查询中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35199127/

相关文章:

PHP PCRE(正则表达式)不支持 UTF-8?

regex - 如何将VI中的搜索选择复制到剪贴板并粘贴到同一文件中?

用于提取电子邮件的正则表达式

java - 如何去掉Java字符串中的大括号?

C# Regex 更改每个匹配项的替换字符串

Mysql - 如果存在则删除表不起作用

mysql - sails mysql : ER_NO_DB_ERROR: No database selected

mysql - 数据截断 : Incorrect datetime value: '04/10/2014 2:21PM'

mysql - 想要一个解决方案使用单个查询分别查找高于限制和低于限制的计数

mysql - 如何在 Doctrine 中将鉴别器列定义为类表继承的 ENUM?