给出几句话。如何编写SQL查询以搜索数据库中存储的字符串是否包含这些单词并以字符串中发现的单词数减少顺序排列。
如果这些单词是众所周知的(而不是动态),并且如果性能不是那么重要,请尝试以下内容:
select c,
if (c like '%sam%', 1, 0)
+ if (c like '%tom%', 1, 0)
+ if (c like '%suse%', 1, 0)
+ if (c like '%jack%', 1, 0)
+ if (c like '%lemon%', 1, 0) as weight
from someTable
order by weight
代码在MySQL 5.6下进行了以下模式:
create table someTable(
c varchar(50)
);
insert into someTable (c) values ("sam tom suse jack lemon");
insert into someTable (c) values ("sam suse some other words");