Create a computed column based on another column in MySQL

≡放荡痞女 提交于 2019-12-06 12:59:45

Because your formatted column depends upon, and is derivable from, the id column, your table design violates 3NF.

Either create a view that has your derived column in it (see this in sqlfiddle):

CREATE VIEW myview AS
SELECT *, substring(cast(100000000 + id AS CHAR(9)), 2) AS formatted_id
FROM mytable

or just start your auto-increment at 10000000, then it will always be 8 digits long:

ALTER TABLE mytable AUTO_INCREMENT = 10000000;

Simple, if the column is unique, it will throw an exception telling that the value already do exists. But if not unique, after 99999999 you'll get error message that the value is truncated.

Alternatives, why not use INT AUTO_INCREMENT? or a custom ID with a combination of date/time, eg

YYMMDD-00000

This will have a maximum record of 99999 records per day. It will reset on the next day.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!