SQL:在LIKE之前使用等于SELECT

时间:2012-03-01 00:55:47

标签: sql sqlite select

我需要在SQLite数据库中查询与给定字符串匹配的项目,或LIKE query%。但是,它并不像

那么简单
SELECT id, type, number FROM roads WHERE number = '12' OR number LIKE '12%'

LIKE 匹配之前,我需要所有相等的匹配。我觉得那里有一个AS,并按顺序排序,但我不确定它是如何工作的。如果可能,我想避免进行两次查询。

3 个答案:

答案 0 :(得分:4)

SELECT id, type, number
FROM roads 
WHERE number = '12' OR number LIKE '12%'
ORDER BY CASE WHEN number = '12' THEN 0 ELSE 1 END, number

答案 1 :(得分:3)

我不确定Sqlite是否支持这种语法,但这是一个想法:

SELECT id, type, number FROM roads WHERE number LIKE '12%'
ORDER BY
   CASE
      WHEN number = '12' THEN 0
      ELSE 1
   END

答案 2 :(得分:1)

SELECT id, type, number 
   FROM roads 
  WHERE number = '12' 
UNION
SELECT id, type, number 
   FROM roads 
  WHERE number LIKE '12%'
        AND NOT EXISTS ( SELECT id, type, number 
                           FROM roads 
                          WHERE number = '12' );