2

Mysql table

create table table1(
   id int(3) zerofill auto_increment primary key,
   username varchar(10)
)
engine=innodb;

Mysql insert query

insert into table1 (username)
       select id from (select id from table1) as a where 
         a.id=last_insert_id();

I am trying to insert into a table by selecting the last id from the same table and the same row,the above queries give the explanation of what i want to do.The insert query gives null value in both the id and username. The expected results is below.

id        username
001         001
002         002
003         003
4

2 回答 2

1

为什么要存储价值?

CREATE TABLE table1 (
   id int(3) zerofill auto_increment PRIMARY KEY
);

CREATE VIEW oh_look_username
  AS
SELECT id
     , LPad(Cast(id As varchar(10)), 3, '0') As username
FROM   table1
于 2013-08-06T22:26:33.240 回答
1

一种可能的方法

INSERT INTO table1 (username)
SELECT LPAD(COALESCE(MAX(id), 0) + 1, 3, '0')
  FROM table1

这是SQLFiddle演示

这种方法的一个缺点是,在重负载下,不同的并发用户可能会得到相同的MAX(id)结果,并且最终会得到具有不同 id 但用户名相同的行。


现在,更精确的方法是使用单独的排序表和BEFORE INSERT触发器

提议的更改表架构

CREATE TABLE table1_seq
(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);

CREATE TABLE table1
(
   id INT(3) ZEROFILL PRIMARY KEY DEFAULT 0,
   username VARCHAR(10)
);

触发

DELIMITER $$
CREATE TRIGGER tg_table1_before_insert
BEFORE INSERT ON table1
FOR EACH ROW 
BEGIN
  INSERT INTO table1_seq VALUES(NULL);
  SET NEW.id = LAST_INSERT_ID(), NEW.username = LPAD(NEW.id, 3, '0');
END$$
DELIMITER ;

table1现在你只需像这样插入新行

INSERT INTO table1 (username) 
VALUES (NULL), (NULL)

结果:

| 身份证 | 用户名 |
-----------------
| 1 | 001 |
| 2 | 002 |

这是SQLFiddle演示

于 2013-08-06T21:43:07.050 回答