【问题标题】:Is there any way to combine LIKE and IN in SQL? [duplicate]有什么方法可以在 SQL 中结合 LIKE 和 IN 吗? [复制]
【发布时间】:2013-06-17 21:58:48
【问题描述】:

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

【问题讨论】:

  • 我猜你可以用正则表达式代替LIKE IN
  • 根据查询,数据库似乎缺乏正常性。更好的数据库结构可能是最好的解决方案。

标签: mysql sql


【解决方案1】:

你不能使用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 with Demo

【讨论】:

  • LEN(CurrentTerm) 应该基于我认为匹配的术语。所以匹配 railway employee 的得分比只匹配 railway 的得分高
  • @MartinSmith 可能,OP 澄清一下会有所帮助。 :)
  • @bluefeet - 抱歉。马丁的意思是正确的。我已经更新了问题以指定 CurrentTerm 它作为匹配项。
  • @Justin808 查看我的编辑,我添加了另一个可能解决您的问题的版本,甚至包括一个演示
【解决方案2】:

您可以使用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 实际上根本不需要,但为了与您的原始查询保持一致。它不需要“%railway employee%”,因为这两者都匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 2015-12-06
    • 2011-03-14
    • 2011-02-23
    • 2016-06-05
    • 2013-07-20
    相关资源
    最近更新 更多