在MySql Regex查询中使用变量

时间:2016-02-04 10:53:47

标签: 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'

感谢。

1 个答案:

答案 0 :(得分:1)

COLLATE表达后每次添加REGEXP

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

相关问题