Ordering dot-delimited numeric sequences (e.g., version numbers)

前端 未结 2 564
自闭症患者
自闭症患者 2021-01-19 16:22

In my database I\'ve column fill this data:

1
1.1
1.1.1
1.1.1.1
1.1.2
1.10
1.11
1.2
1.9

I want to sort it, to get result looks like this:

2条回答
  •  伪装坚强ぢ
    2021-01-19 16:53

    Casting to cidr will do the trick (if the numbers are well-behaved)

    DROP table meuk;
    CREATE table meuk
            ( id SERIAL NOT NULL PRIMARY KEY
            , version text
            );
    
    
    INSERT INTO meuk(version) VALUES
     ('1' )
    , ('1.1' )
    , ('1.1.1' )
    , ('1.1.1.1' )
    , ('1.1.2' )
    , ('1.10' )
    , ('1.11' )
    , ('1.2' )
    , ('1.9' )
            ;
    
    SELECT * FROM meuk
    ORDER BY version::cidr
            ;
    

    Result:

    INSERT 0 9
     id | version 
    ----+---------
      1 | 1
      2 | 1.1
      3 | 1.1.1
      4 | 1.1.1.1
      5 | 1.1.2
      8 | 1.2
      9 | 1.9
      6 | 1.10
      7 | 1.11
    (9 rows)
    

提交回复
热议问题