2014-01-27 106 views
0

我试图在数据库中插入2行,第二行需要第一行的自动递增ID。 我已经与LAST_INSERT_ID()测试,但我有一个MysqlIntegrityConstraintViolationException如何使用MySQL获取最后一个ID插入

Cannot add or update a child row : a foreign key constraint fails ('customer_user_role', CONSTRAINT 'fk_customer_user_role_customer_id' FOREIGN KEY ('customer_user_role_id') REFERENCES 'customer' ('customer_id') ON DELETE NO ACTION ON UPDATE NO ACTION)

我的SQL请求是:

sqlu"INSERT INTO customer (name, email, phone, isActivated) VALUES ($name, $email, $phoneNumber, $isActivated)"

sqlu"INSERT INTO customer_user_role (customer_id, user_id, customer_roletype_id) VALUES (LAST_INSERT_ID(), $userId, $roleTypeId)"

(我的工作宽度播放&油滑所以这为什么特定语法)

当我在PhpMyAdmin上执行此操作时,会显示相同的错误,我不知道如何继续...

回答

0

请看看这个http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html。在插入第二行之前,获取该id并继续。不应该很难。

+0

我已经看过这个文档,它使我错误,用'last_insert_id()'和'mysql_insert_id()' – Azuken

+0

你调试过吗?首先调试看看你是否真的获得了价值。您的列是否设置为自动增量? – johnny

+0

当我从PHPMyAdmin执行时,它返回我0 ...插入课程后。 – Azuken

0

尝试这种情况:

 set @last_inserted_id = LAST_INSERT_ID(); 

然后使用@last_inserted_id作为值而插入到另一个表。

+0

我试过了,它不起作用,也许是因为光滑的语法 – Azuken

相关问题