简体   繁体   English

如何确保mysql列具有4个字符

[英]how to ensure mysql column has 4 character

how to ensure mysql column has 4 character ? 如何确保mysql列具有4个字符?

Due to using the MATCH function with minimum 4 char, i want my primary key which is a INT to be at least 4 char. 由于使用了至少4个字符的MATCH函数,我希望我的主键INT至少为4个字符。

How can i do it ? 我该怎么做 ?

eg. 例如。 1 will be 0001 in sql table sql表中的1将是0001

Use ZEROFILL attribute of column. 使用列的ZEROFILL属性。 Alter your Primary key column to have zerofill enabled. 更改您的主键列以启用零填充。

Try this: 尝试这个:

ALTER TABLE `tablename` CHANGE
COLUMN `id` `id` INT(4) ZEROFILL NOT NULL AUTO_INCREMENT ;

You can use MySQL's LPAD function: 您可以使用MySQL的LPAD函数:

SELECT LPAD('1',4,'0');
    -> '0001'

Docs here . 文档在这里

Assuming your primary key is an auto-incremented id. 假设您的主键是一个自动递增的ID。

  1. Temporarily take the auto-increment off. 暂时取消自动递增。
  2. Add 999 to every id. 将999添加到每个ID。 (Of course if other tables use this id as a foreign key, you are going to have to adjust them, too). (当然,如果其他表将此ID用作外键,则也必须对其进行调整)。
  3. Re-add the auto-increment, but make sure that it starts at at least 1000. See: How to set initial value and auto increment in MySQL? 重新添加自动增量,但是确保它至少开始于1000。请参阅: 如何在MySQL中设置初始值和自动增量?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM