0

I have a mytable table in my MySQL database.

It contains the following columns:

  • id (INT) PRIMARY KEY - AUTO INCREMENT - DEFAULT NONE
  • name (VARCHAR (220)) - DEFAULT NULL
  • code (VARCHAR (220)) - DEFAULT NULL

Is it possible that if I insert something in this table I want the code column to autogenerate its value based on the columns id and name.

If I tried to run this example query:

INSERT INTO mytable(name) VALUES ('myname');

I want to get the following result:

+----+--------+-------+
| id | name   | code  |
+----+--------+-------+
| 1  | myname | my1   |
+----+--------+-------+

The code column default value must be the first 2 characters of myname which is my plus the id column.

I can actually do this using PHP code but I think there must be a way using MySQL only.

  • You have two options with and without auto increment on id link – Sam Dec 28 '18 at 3:34
  • I vote for PHP -- you will have more flexibility and you can respond faster to odd names that don't follow whatever algorithm you pick. – Rick James Dec 28 '18 at 4:12
  • @Sam The value of calculated field cannot be altered :( if new value and calculated value are not equal. – Akina Dec 28 '18 at 5:32
2

If the code field values are altered never the solution is trivial - look on the fiddle provided in Sam's comment. The only point I'd recommend to specify VIRTUAL attribute for calculated field explicitely.

If the code field values specified in a question are default only, and they can be altered from the default value freely either when inserting or by data updating, I'd recommend to make this field NULLable and use NULL value as a mark that the value is default one and must be calculated in a query. In all places where you need the value of this field you will use the below expression instead of direct field's value selection:

SELECT  ..., 
        COALESCE(code, CONCAT(SUBSTRING(name,1,2),id)) code, 
        ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.