将字段值设置为ID值

时间:2012-10-27 19:02:18

标签: mysql insert

我正在规范我的数据库,我试图将字段的值设置为与该行的ID相同,以便我可以连接表。

我尝试使用LAST_INSERT_ID(),但它不起作用。我没有收到错误,但我只收到零。

INSERT INTO `eleves` (`user_id`, 
`first_name`, `last_name`, 
`username`, `groupe`, 
`password`, `courriel`, 
`active`, `auteur`, 
`citations`, `absurde`, 
`vocabulaire`,  `analyse`, 
`themes`, `personnages`) 
VALUES (NULL, 
'Jane', 'Doe', 
'janedoe', '400', 
'password', 'jane@doe.com', 
'1', LAST_INSERT_ID(), 
LAST_INSERT_ID(), LAST_INSERT_ID(), 
LAST_INSERT_ID(), LAST_INSERT_ID(), 
LAST_INSERT_ID(), LAST_INSERT_ID());

谢谢!

2 个答案:

答案 0 :(得分:0)

删除它们周围的单引号

INSERT INTO `eleves`(`user_id`, `username`, `auteur`, `citations`, `absurde`) 
VALUES (NULL,'janedoe',LAST_INSERT_ID(),LAST_INSERT_ID(),LAST_INSERT_ID());

答案 1 :(得分:0)

看来,在你的MySQL会话期间没有插入自动生成的id。因此,要填充last_insert_id()的字段必须是zero而不是empty(NULL?,SPACE?)。

尝试在表中定义具有自动增量的主键,并让您生成新记录。看看会发生什么!

请参阅以下示例:

$ mysql -u ravi -p test
Enter password: ********
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2 to server version: 5.0.22-community-nt

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                0 |
+------------------+
1 row in set (0.00 sec)

mysql> create table eleves( user_id int not null auto_increment primary key, username varchar(10), auteur int, citations int, absurde int );
Query OK, 0 rows affected (0.06 sec)

mysql> insert into eleves( username, auteur, citations, absurde )
    -> values( 'janedoe1', last_insert_id(), last_insert_id(), last_insert_id() );
Query OK, 1 row affected (0.03 sec)

mysql> select * from eleves;
+---------+----------+--------+-----------+---------+
| user_id | username | auteur | citations | absurde |
+---------+----------+--------+-----------+---------+
|       1 | janedoe1 |      0 |         0 |       0 |
+---------+----------+--------+-----------+---------+
1 row in set (0.00 sec)

mysql> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                1 |
+------------------+
1 row in set (0.00 sec)

mysql> insert into eleves( username, auteur, citations, absurde )
    -> values( 'janedoe2', last_insert_id(), last_insert_id(), last_insert_id() );
Query OK, 1 row affected (0.01 sec)

mysql> select * from eleves;
+---------+----------+--------+-----------+---------+
| user_id | username | auteur | citations | absurde |
+---------+----------+--------+-----------+---------+
|       1 | janedoe1 |      0 |         0 |       0 |
|       2 | janedoe2 |      1 |         1 |       1 |
+---------+----------+--------+-----------+---------+
2 rows in set (0.00 sec)

mysql> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
|                2 |
+------------------+
1 row in set (0.00 sec)

mysql>