1

I have a database table in mysql

create table userstable ( id int not null auto_increment, name varchar(80) not null, username varchar(80) not null, primary key(id) ); 

How to add new row in mysql database, so that username will be 'name'+('id'*100)

Example :

ID name username 1 A A100 2 B B200 3 C C300 4 user user400 
2
  • You need to use triggers for that. Create a AFTER INSERT trigger for that table Commented Jul 31, 2015 at 8:54
  • Just to confirm what's obvious from the DDL: You are fine with duplicates in username. e.g. (1,A1,A1100) and (11,A,A1100) Commented Jul 31, 2015 at 9:20

3 Answers 3

2

You need trigger for that process. Create the following trigger

CREATE TRIGGER username_change BEFORE INSERT ON userstable FOR EACH ROW BEGIN SET NEW.username = CONCAT(NEW.name,(NEW.id*100)); END 

OR

INSERT INTO userstable (id,name, username) VALUES (2, 'B', CONCAT(name,(id*100))); 

Try this.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer,it's work, but can i solve this using subquery / query without using trigger?
@Divyang - Check the insert query I have given.
0

You'll need to write a trigger or update the field after insertion. A similar question provides more insight:

Can you access the auto increment value in MySQL within one statement?

Comments

0

As @ArunKrish correctly pointed out, you may use TRIGGER to update the data as part of the insert. Another option is to use view:

CREATE VIEW v1 AS SELECT id,name,CONCAT(name,id*100) AS username FROM userstable; 

You may also use the query as-is, without view:

SELECT id,name,CONCAT(name,id*100) AS username FROM userstable; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.