2013-06-20 93 views
0

現在我有以下SQL:有什麼辦法可以在SQL中結合LIKE和IN?

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

我想你可以使用正則表達式而不是'LIKE IN'。 –

+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; 

SQL Fiddle with Demo

+1

'LEN(CurrentTerm)'應該基於我認爲匹配的術語。因此,匹配'鐵路員工'的人得分高於那些匹配'鐵路'的人# –

+0

@MartinSmith可能,這將有助於它在OP中澄清。 :) – Taryn

+0

@bluefeet - 對不起。馬丁對我的意思是正確的。我已經更新了這個問題來指定'CurrentTerm'它是匹配項。 – Justin808

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。它不需要「%鐵路員工%」,因爲它符合兩者。

相關問題