我正在搜索包含列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
谢谢大家的帮助!
答案 0 :(得分: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%';
答案 1 :(得分: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
这是Fiddle。
祝你好运。答案 2 :(得分: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, '%')