现在我有以下SQL:
select MAX(score) as score, title from
(
select 2 as score, title from tableName WHERE title LIKE '%railway employee%'
union
select 1 as score, title from tableName WHERE title LIKE '%railway%'
union
select 1 as score, title from tableName WHERE title LIKE '%employee%'
) as t1
group by title
order by score DESC
我希望能够做到这样的事情:
select MAX(score) as score, title from
(
select LEN(CurrentTerm) as score, title from tableName WHERE title LIKE IN ('%railway employee%', '%railway%', '%employee%')
) as t1
group by title
order by score DESC
CurrentTerm
将是匹配的术语,而不是表格中的列。在SQL中是否有任何类似的东西,特别是MySQL?
答案 0 :(得分:4)
您无法使用LIKE IN
,但可以使用OR
:
select MAX(score) as score, title from
(
select LEN(CurrentTerm) as score, title
from tableName
WHERE title LIKE '%railway employee%'
OR title LIKE '%railway%'
OR title LIKE '%employee%'
) as t1
group by title
order by score DESC;
您可能能够使用类似于以下内容的内容,这些内容使用3个搜索词的派生表并带有分数值:
select max(score) as score, title
from
(
select 2 score, 'railway employee' term union all
select 1 score, 'railway' term union all
select 1 score, 'employee' term
) d
inner join tableName t
on title like concat('%', term, '%')
group by title
order by score desc;
答案 1 :(得分:3)
您可以使用or
:
select MAX(score) as score, title
from (select LEN(CurrentTerm) as score, title
from tableName
WHERE title LIKE '%railway employee%' or
title like '%railway%' or
title like '%employee%'
) as t1
group by title
order by score DESC
编辑:
我知道,你在数据库中没有“CurrentTerm”。这是一个更好的版本:
select max(case when title LIKE '%railway employee%' then 2
when title LIKE '%railway%' then 1
when title LIKE '%employee%' then 1
end) as score, title
from tableName
WHERE title like '%railway%' or title like '%employee%'
group by title
order by score DESC
实际上根本不需要最终where
,但与原始查询保持一致。它不需要“%铁路员工%”,因为它匹配两者。