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

前端 未结 10 2125
南旧
南旧 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:53

    Finally, I found another way to sort version strings.

    I just justify the string before storing into de database in a way it is sortable. As I am using the python Django framework, I just have created a VersionField that 'encode' the version string while storing and 'decode' it while reading, so that it is totally transparent for the application :

    Here my code :

    The justify function :
    
    def vjust(str,level=5,delim='.',bitsize=6,fillchar=' '):
        """
        1.12 becomes : 1.    12
        1.1  becomes : 1.     1
        """
        nb = str.count(delim)
        if nb < level:
            str += (level-nb) * delim
        return delim.join([ v.rjust(bitsize,fillchar) for v in str.split(delim)[:level+1] ])
    
    The django VersionField :
    
    class VersionField(models.CharField) :
    
        description = 'Field to store version strings ("a.b.c.d") in a way it is sortable'
    
        __metaclass__ = models.SubfieldBase
    
        def get_prep_value(self, value):
            return vjust(value,fillchar=' ')
    
        def to_python(self, value):
            return re.sub('\.+$','',value.replace(' ',''))
    

提交回复
热议问题