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.
We can use a literal in CONCAT Function. A literal is a number, character, or date that includes the SELECT statement.
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.
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.
Advertisements. SQL CONCAT function is used to concatenate two strings to form a single string.
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)
);
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 |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With