【问题标题】:How to set order by condition on sqlite based on where condition?如何根据where条件在sqlite上按条件设置顺序?
【发布时间】:2020-12-23 03:45:20
【问题描述】:

我在 sqlite db 中关注查询和国家/地区列表

select * from country where name like 'searchString%' or name like '% searchString%'

如果 searchString 是 'in',结果会是这样的

1   British Indian Ocean Territory
2   India
3   Indonesia

但我需要第一个条件的结果(如 'searchString%' )结果应该是第一位的

1   India
2   Indonesia
3   British Indian Ocean Territory

我需要在单个查询中完成此操作。这可能吗?

【问题讨论】:

  • 如果可以删除 MySQL、SQL Server 和 PostgreSQL,请不要标记无关的 RDBMS。谢谢
  • 我只是标记了那些,因为这些查询大多是相同的逻辑。所以只标记了那个
  • 好的,有人这样做了。我添加了与问题相关的新标签。

标签: sqlite android-sqlite sql-order-by


【解决方案1】:

WHERE 子句中只需要 1 个条件,条件:

name LIKE 'in%' DESC

ORDER BY 子句中将返回顶部以'in' 开头的国家/地区:

SELECT * 
FROM country 
WHERE name LIKE '%in%'
ORDER BY name LIKE 'in%' DESC, name

另一种选择是使用字符串函数:

SELECT * 
FROM country 
WHERE name LIKE '%in%'
ORDER BY instr(lower(name), 'in'), name

请参阅demo
结果:

> id | name                          
> -: | :-----------------------------
>  2 | India                         
>  3 | Indonesia                     
>  1 | British Indian Ocean Territory

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 2017-03-31
    • 1970-01-01
    相关资源
    最近更新 更多