【问题标题】:SQLITE: pull items in the same order as IN arraySQLITE:以与 IN 数组相同的顺序拉取项目
【发布时间】:2019-05-22 13:37:36
【问题描述】:

我有以下疑问:

SELECT * from tWords where WordAton IN ("bbb", "aaa2", "ccc", "aaa1")

查询首先返回“aaa1”的结果,然后是“aaa2”的结果,然后是“bbb”的结果,然后是“ccc”的结果。有没有办法按照输入数组的顺序返回结果,这意味着首先是“bbb”的结果,然后是“aaa2”的结果......等等。

提前谢谢你。

【问题讨论】:

    标签: sqlite


    【解决方案1】:

    您可以像这样应用条件排序:

    SELECT * 
    from tWords 
    where WordAton IN ('bbb', 'aaa2', 'ccc', 'aaa1')
    order by case WordAton
      when 'bbb' then 1
      when 'aaa2' then 2
      when 'ccc' then 3
      when 'aaa1' then 4
    end 
    

    【讨论】:

      【解决方案2】:

      在 SQL(不仅仅是 SQLite)中,总是按给定顺序返回行的唯一方法是使用 SQL ORDER BY ... 子句。所以简短的回答是“不”,没有简单方法可以按照IN (...) 子句的内容给出的顺序返回行。

      可以使用公用表表达式 (CTE) 来定义排序顺序,但这通常不值得麻烦。这与按IN (...) 子句的内容排序不同,但看起来 相同。 (您按照 CTE 中指定的排序顺序进行排序。)

      with ordered_words as (
        select 1 as sort_order, 'bbb' as WordAton union
        select 2,               'aaa2' union
        select 3,               'ccc' union
        select 4,               'aaa1'
      )
      select t.WordAton
      from tWords t
      join ordered_words o on t.WordAton = o.WordAton
      where t.WordAton in ('bbb', 'aaa2', 'ccc', 'aaa1')
      order by o.sort_order;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多