2013-02-25 41 views
2

嗨,大家好,我尝试存储问题&答案在2和表1个使用SQL查询:SQL查询使用多个插件和多LAST_INSERT_ID()的工作不

INSERT INTO questions (question, level_ID) VALUES ('hello', '1'); INSERT INTO answers (questions_ID, answer, ok) VALUES (LAST_INSERT_ID(),'doei',0), (LAST_INSERT_ID(),'ciao',1); 

如果我执行代码的phpMyAdmin的SQL箱它工作得很好,但如果我在PHP代码生成脚本,执行它,它返回以下错误:

您的SQL语法错误;检查与您的MySQL服务器版本对应的手册,以便在'INSERT INTO answers(questions_ID,answer,ok)'附近使用正确的语法。'VALUE(LAST_INSERT_ID(),'doei',0'at line 2

我无法'看不到我在做什么错了...任何人??

在此先感谢。

+0

显示你的PHP代码。 – Karl 2013-02-25 11:21:59

+0

我的猜测是,您在一次调用中执行所有查询,但是您使用的库不支持多个语句。 – 2013-02-25 11:24:45

回答

1

它不是SQL查询而设置的查询。
phpMyAdmin的只是分割你的一套,然后分别执行查询。

所以,你必须做的。
只要运行他们一个接一个。

不要改变任何东西。不需要额外的变量或其他。
只需在2个单独的连续调用中一个接一个地运行相同的查询。
就是这样。

+2

...或使用[mysqli :: multi_query()](http://php.net/manual/en/mysqli.multi-query.php)。 – 2013-02-25 11:25:25

+0

好男人谢谢。如果我分开查询并单独运行,确实可行。但是因为我需要从LAST_INSERT_ID()生成的ID我把查询放在一起。所以现在我必须使用一个变量来存储生成的ID? – 2013-02-25 11:38:04

+0

@ArjoPost是的,你需要一个变量传递给第二个SQL。你完成了。 – Hamad 2013-02-25 11:57:12

0

the manual

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

所以你不需要只要你使用相同的连接收拾所有查询到一个SQL数据库调用。但是如果你想想要这样做,你需要确保你的数据库库和函数支持该功能。