How to compare version string (“x.y.z”) in MySQL?

前端 未结 10 2135
南旧
南旧 2020-12-16 14:02

I have firmware version strings into my table (like \"4.2.2\" or \"4.2.16\")

How can I compare, select or sort them ?

I cannot use standard strings compariso

10条回答
  •  天命终不由人
    2020-12-16 14:54

    Lots of good solutions here, but I wanted a stored function that would work with ORDER BY

    CREATE FUNCTION standardize_version(version VARCHAR(255)) RETURNS varchar(255) CHARSET latin1 DETERMINISTIC NO SQL
    BEGIN
      DECLARE tail VARCHAR(255) DEFAULT version;
      DECLARE head, ret VARCHAR(255) DEFAULT NULL;
    
      WHILE tail IS NOT NULL DO 
        SET head = SUBSTRING_INDEX(tail, '.', 1);
        SET tail = NULLIF(SUBSTRING(tail, LOCATE('.', tail) + 1), tail);
        SET ret = CONCAT_WS('.', ret, CONCAT(REPEAT('0', 3 - LENGTH(CAST(head AS UNSIGNED))), head));
      END WHILE;
    
      RETURN ret;
    END|
    

    to test:

    SELECT standardize_version(version) FROM (SELECT '1.2.33.444.5b' AS version UNION SELECT '1' UNION SELECT NULL) AS t;
    

    renders:

    00001.00002.00033.00444.00005b
    00001
    (null)
    

    And allows for comparisons of almost any set of versions, even ones with letters.

提交回复
热议问题