5

我想在 MySQL 中插入数据并在字段上自动命名,username但我该怎么做呢?
目前表中数据为:

+----+----------+
| 编号 | 用户名 |
+----+----------+
| 1 | 管理员1 |
| 2 | 管理员2 |
+----+----------+

我尝试使用这个 sql 但它不能:

插入到`tbl_user`(
`用户名`
)
价值观(
CONCAT('admin',(SELECT MAX(SUBSTRING_INDEX(`username`,'admin',-1))+1 FROM `tbl_user`))
);

并得到错误消息#1093 - You can't specify target table 'tbl_user' for update in FROM clause

我想要的最终结果是:

+----+----------+
| 编号 | 用户名 |
+----+----------+
| 1 | 管理员1 |
| 2 | 管理员2 |
| 6 | 管理员3 |
| 9 | 管理员4 |
+----+----------+

那可能吗?谢谢。

4

2 回答 2

6

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)
);
于 2013-01-25T14:24:58.937 回答
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 |
于 2013-01-25T14:29:37.827 回答