Padding the beginning of a mysql INT field with zeroes

后端 未结 2 1592
余生分开走
余生分开走 2020-12-18 03:56

I have an INT field in a large MySQL database containing incremental numbers in an INT field. These numbers are currently regular autoincrement numbers (1, 2, 3) but I need

相关标签:
2条回答
  • 2020-12-18 04:36

    There is no such thing as having leading zeroes on data in a numeric field in the database; the data just isn't stored that way, any more than it is stored in roman numerals. All you've got is the number three; so if you want to get the string "003" out, you've got two options:

    • Change to use a string field in the database: not recommended because you can't easily get incrementing numbers.
    • Format the number as you retrieve it from the database to add leading zeroes: better, but it has its own disadvantages - e.g. comparisons will be slower because they aren't indexed.
    0 讨论(0)
  • 2020-12-18 04:37

    You can add a ZEROFILL attribute to the column to pad the data in the database or, when querying,

    SELECT LPAD(CONVERT(`col`,VARCHAR(3)),3,'0')
    

    to retreive the data formatted as a 3 digit number

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