MySQL:在同一查询中插入和选择
我要创建棘手的 SQL
查询,如果可能的话,这将为我节省大量 PHP 代码。
因此,我有一个 HTML 表单,访问者可以在其中创建用户帐户,其中包含字段名称、电子邮件、密码、兴趣。
对于名称、电子邮件和密码,我有一个简单的INSERT
查询来将此信息输入数据库users
,但是interests字段可以有多个条目,因此该数据存储在多对多连接表中(interests
、user_interests< /代码>)。
为了让我在表 user_interests 中输入这些兴趣,我需要获取从初始 INSERT
查询自动递增的用户 ID 号,并在另一个 INSERT 上循环用户选择的每个“兴趣”。我可以在一个 SQL 查询中完成这一切吗?
I have tricky SQL
query to create, which if possible will save me a lot of PHP code.
So I have an HTML form where a visitor can create a user account with the fields name, email, password, interests.
For the name, email and password I have a simple INSERT
query to enter this info into the database users
, however the interests field can have multiple entries so this data is stored in many-to-many join tables (interests
, user_interests
).
In order for me enter these interests in the table user_interests, I need to obtain the User ID number which was auto-incremented from the initial INSERT
query plus loop over another INSERT for each "interest" the user has chosen. Can I accomplish this all in one SQL query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想使用一个命令来完成此操作,那么学习如何编写 MySql 存储过程听起来是一个很好的案例。结果也会快得多。
http://dev.mysql.com /doc/refman/5.0/en/stored-routines-last-insert-id.html
http://dev.mysql.com/doc/refman /5.0/en/sql-syntax-compound-statements.html
If you want to do this with one command, then it sounds like a good case to learn how to write MySql stored procedures. The result will be much faster too.
http://dev.mysql.com/doc/refman/5.0/en/stored-routines-last-insert-id.html
http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-compound-statements.html
嗯,在 MySQL 中,INSERT 语句仅插入到一张表中。所以不,不可能通过单个查询来完成此任务。但您可以通过两个查询来完成。 MySQL 支持一种语法,您可以使用单个查询插入多行:
PS 我确实正确理解兴趣是一个分类器,并且向
interests
表添加新行超出了这个问题的范围,正确的?Well, in MySQL an INSERT statement only inserts into one table. So no, it's impossible to accomplish this with a single query. But you can do it with two queries. MySQL supports a syntax where you can insert multiple rows with a single query:
P.S. I do understand correctly that the interests are a classifier, and adding new rows to the
interests
table is beyond the scope of this question, right?