0

现在我有以下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?

4

2 回答 2

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;

请参阅带有演示的 SQL Fiddle

于 2013-06-20T21:16:44.267 回答
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

finalwhere实际上根本不需要,但为了与您的原始查询保持一致。它不需要“%railway employee%”,因为这两者都匹配。

于 2013-06-20T21:16:55.650 回答