-1

我正在规范我的数据库,我正在尝试将字段的值设置为与该行的 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());

谢谢!

4

2 回答 2

0

删除它们周围的单引号

INSERT INTO `eleves`(`user_id`, `username`, `auteur`, `citations`, `absurde`) 
VALUES (NULL,'janedoe',LAST_INSERT_ID(),LAST_INSERT_ID(),LAST_INSERT_ID());
于 2012-10-27T19:03:28.760 回答
0

看来,在您的 MySQL 会话期间,没有插入自动生成的 id。因此,对于您要填写的字段,last_insert_id()必须是 azero而不是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>
于 2012-10-27T19:53:37.377 回答