سؤال

how to ensure mysql column has 4 character ?

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.

How can i do it ?

eg. 1 will be 0001 in sql table

هل كانت مفيدة؟

المحلول

Use ZEROFILL attribute of column. 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:

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

Docs here.

Assuming your primary key is an auto-incremented id.

  1. Temporarily take the auto-increment off.
  2. Add 999 to every id. (Of course if other tables use this id as a foreign key, you are going to have to adjust them, too).
  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?
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top