Storing leading zeros of integers in MySQL database as INTEGER

后端 未结 4 381
渐次进展
渐次进展 2020-12-05 07:32

I need MySQL to store numbers in a integer field and maintain leading zeros. I cannot use the zerofill option as my current field is Bigint(16) and numbers can vary in amoun

相关标签:
4条回答
  • 2020-12-05 07:59

    You can not store integer with leading zeroes. One way is keeping it in varchar as well as int columns. In this case, you need two columns, one value and the other intValue and while sorting, you can use the intValue for sorting. This is easy to implement.

    Select Value from Table order by intValue;
    

    The other option can be using two columns, one valu and othe NumOfZero and use these for the desired results. This is complex, but might be light on the DB.

    0 讨论(0)
  • 2020-12-05 08:01

    Change the structure of the field and make the Attributes UNSIGNED_ZEROFILL to keep the zeros.

    But you should be careful to the Length of the field, because it's gonna return all the rest numbers to zeros so put the length of your field

    0 讨论(0)
  • 2020-12-05 08:07

    You can still sort the string(CHAR/VARCHAR) columns like integer using CAST

    ORDER BY CAST(`col_name` AS SIGNED) DESC
    

    So, you can store them in CHAR/ VARCHAR type fields.

    0 讨论(0)
  • 2020-12-05 08:14

    Keep the numbers stored as integers.

    Then use function LPAD() to show the numbers (left) padded with zeros:

    SELECT LPAD( 14, 7, '0') AS padded;
    
    | padded  |
    -----------
    | 0000014 |
    

    If the number of zerofill characters is variable, add another column in the table with that (zerofill) length.

    0 讨论(0)
提交回复
热议问题