Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql concat from select result

Tags:

mysql

I would like to insert data in MySQL with automatic naming on field username but how i can do it?.
Currently data at table is:

+----+----------+
| id | username |
+----+----------+
|  1 | admin1   |
|  2 | admin2   |
+----+----------+

I try using this sql but it's can't:

INSERT INTO `tbl_user` (
`username`
)
VALUES (
CONCAT('admin',(SELECT MAX(SUBSTRING_INDEX(`username`,'admin',-1))+1 FROM `tbl_user`))
);

and get error message #1093 - You can't specify target table 'tbl_user' for update in FROM clause

Final result i want is:

+----+----------+
| id | username |
+----+----------+
|  1 | admin1   |
|  2 | admin2   |
|  6 | admin3   |
|  9 | admin4   |
+----+----------+

is that possible? thanks.

like image 616
Idham Perdameian Avatar asked Jan 25 '13 14:01

Idham Perdameian


People also ask

Can we use concat in select statement?

We can use a literal in CONCAT Function. A literal is a number, character, or date that includes the SELECT statement.

How do I concatenate a query in MySQL?

CONCAT() function in MySQL is used to concatenating the given arguments. It may have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string.

Can I concatenate multiple MySQL rows into one field?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value.

What is select concat?

Advertisements. SQL CONCAT function is used to concatenate two strings to form a single string.


2 Answers

You can use a trigger that would update the column username after an insert. Here's some more information on how to actually do this: http://www.roseindia.net/sql/trigger/mysql-trigger-after-insert.shtml

Edit

I forgot that MySQL won't allow you to update a table from a trigger declared on the same table.

However, this should do what you're trying to do:

SET @id := (SELECT id FROM YOUR_TABLE ORDER BY id DESC LIMIT 1);
INSERT INTO YOUR_TABLE (username) VALUES(
   CONCAT("ADMIN", @id + 1)
);
like image 166
Ray Z Avatar answered Oct 09 '22 15:10

Ray Z


Query:

SQLFIDDLEExample

INSERT INTO `tbl_user` (
`username`
)
VALUES (
CONCAT('admin',(SELECT MAX(CAST(REPLACE(`username`,'admin','') AS SIGNED INTEGER))+1 
                FROM (SELECT * FROM tbl_user) t))
);

Result:

|     ID | USERNAME |
---------------------
|      1 |   admin1 |
|      2 |   admin2 |
| (null) |   admin3 |
like image 24
Justin Avatar answered Oct 09 '22 16:10

Justin