0

我正在搜索包含列 ID、消息的消息表中的特定单词

我目前正在使用表格的案例

select message_table.id, 
    case 
    when message_table.message like "%word1%" then 'word1'
    when message_table.message like "%word2%" then 'word2'
    when message_table.message like "%word3%" then 'word3'
    end as Filter
from message_table where Filter is not null

如果 Message 列中的一行具有值 ;word1,word2,word3; 目前只返回一个。

我想拥有它们。认为 concat/group concat 可能会有所帮助,但不太确定如何为找到的每个单词生成一行。

将不胜感激任何建议!

编辑:提供的所有解决方案看起来都不错,必须全部尝试,看看哪个具有最佳性能。我当前的查询已经比我想要的要长,稍后会返回结果

Edit2:明智的获胜者速度是(甚至比我上面的情况还要快)。

select id, group_concat(word)
from
   (
   select id, 'word1' as Word from message_table where message like "%word1%" union
   select id, 'word2' from message_table where message like "%word2%" union
   select id, 'word3' from message_table where message like "%word3%" 
   ) alias
   group by 1

谢谢大家的帮助!

4

3 回答 3

1

如果要为每个单词返回单独的行,最简单的方法是本质上进行三个查询并将它们与 UNION 放在一起:

SELECT id, 'word1' FROM message_table WHERE Filter IS NOT NULL AND message like '%word1%'
  UNION
SELECT id, 'word2' FROM message_table WHERE Filter IS NOT NULL AND message like '%word2%'
  UNION
SELECT id, 'word3' FROM message_table WHERE Filter IS NOT NULL AND message like '%word3%';
于 2013-01-30T15:39:05.083 回答
1

根据您的输出需求,这样的事情应该使用CONCAT

select message_table.id,
    concat(
       case 
          when message_table.message like "%word1%" then 'word1'
          else ''
       end,
       case
          when message_table.message like "%word2%" then 'word2'
          else ''
       end,
       case
          when message_table.message like "%word3%" then 'word3'
          else ''
       end)
    as Filter
from message_table

这是小提琴

祝你好运。

于 2013-01-30T15:39:21.780 回答
1

您可以通过加入来做到这一点:

select mt.message_table_id, words.word as filter
from message_table mt join
     (select 'word1' as word union all select 'word2' union all select' word3'
     ) words
     on mt.message like concat('%', words.word, '%')
于 2013-01-30T15:40:57.783 回答