【问题标题】:How to compare version strings in sqlite?如何比较sqlite中的版本字符串?
【发布时间】:2021-11-21 06:21:34
【问题描述】:

我有一列包含版本号作为字符串,如:

  • 2.7.0.0
  • 2.6.12.0
  • 3.30.3.0
  • 更多

如何选择所有版本号低于 2.7.0.0 的条目?

自从my last question 被关闭是因为obviouse answere 我的问题是这样的:

WITH split(word, str) AS (
    SELECT '', '2.7.0.0'||'.'
    UNION ALL SELECT
    substr(str, 0, instr(str, '.')),
    substr(str, instr(str, '.')+1)
    FROM split WHERE str!=''
) SELECT word FROM split WHERE word!='';

对此我有多个问题:

  • 此示例仅在. 处拆分字符串。如何将其构建到查询中,而不仅仅是将字符串硬编码到其中? (尝试用(select version from software) 替换'2.7.0.0' 没有运气)
  • 我需要将版本2.7.0.0 放在哪里以便在此查询中进行比较?

编辑:

我只使用第一个数字:

select version from software where (
    select word as major from (WITH split(word, str) AS (
        SELECT '', version||'.'
        UNION ALL SELECT
        substr(str, 0, instr(str, '.')),
        substr(str, instr(str, '.')+1)
        FROM split WHERE str!=''
    ) SELECT word FROM split WHERE word!='' LIMIT 1) where word = "2"
)

【问题讨论】:

  • 澄清您的问题。您想拆分字符串以获取子值,还是将它们相互比较以获得 >、
  • @MarkBenningfield 它写在标题“[...] compre version string [...]”以及“如何选择版本号lower 比 [...]" 我显然是想比较它。我没有问如何拆分版本字符串..
  • 好吧,你是说select "colName" from "tableName" where "colName" < '2.7.0.0' 不起作用吗?它应该。
  • fml,这确实有效...我没有尝试它,因为我从没想过它会起作用...我确实想过复杂的方法

标签: sql sqlite


【解决方案1】:

如果部分的数量是固定的,4 部分总是可以使用派生表(子查询)和 instr substr 函数。例如

SELECT productId, major
          , cast(substr(version, 0, instr(version, '.')) as decimal)  minor
          , cast(substr(version, instr(version, '.') + 1) as decimal(6,3)) build
FROM (
    SELECT productId, cast(substr(version, 0, instr(version, '.')) as decimal)  major, substr(version, instr(version, '.') + 1) version
    FROM (
       -- sample data
       select 1 productId, '2.7.0.0' version
       union all 
       select 2,  '2.6.12.0'
       union all 
       select 3,  '3.30.20.1' 
       union all 
       select 4,  '3.30.3.1' 
       ) myTable
    )t
 order by major, minor, build

输出

productId   major   minor   build
2   2   6   12
1   2   7   0
4   3   30  3.1
3   3   30  20.1

【讨论】:

    猜你喜欢
    • 2012-04-29
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2022-01-10
    • 2011-02-25
    • 2010-09-16
    • 2018-01-23
    相关资源
    最近更新 更多