简体   繁体   English

需要MySQL帮助-在尽可能少的查询中添加问题/答案?

[英]MySQL help needed - Add questions/answers in the fewest queries possible?

I'm writing a very simple PHP script for surveys. 我正在为调查编写一个非常简单的PHP脚本。 At this time, it can only handle one survey at a time. 目前,它一次只能处理一项调查。 The database schema looks like this: 数据库模式如下所示:

table 1: questions
    primary key: question_id
    second field: question
table 2: answers
    primary key: answer_id
    second field: answer
    foreign key: question_id

I have an admin section in this script that allows me to add one question at a time. 我在此脚本中有一个管理部分,可让我一次添加一个问题。 I've also made it possible to add a variable number of answers to each question. 我还可以为每个问题添加可变数量的答案。 I'm having trouble with two things: 我在两件事上遇到麻烦:

  1. How can I make sure that the variable number of answers being added all have foreign keys that link to the correct question? 如何确定要添加的可变数量的答案都具有链接到正确问题的外键? Do I need to INSERT the question, then SELECT it to find its ID, then INSERT the answers? 我是否需要INSERT问题,然后SELECT问题以找到其ID,然后INSERT答案? I feel like there should be a better way to do it. 我觉得应该有一个更好的方法。
  2. What's the best way to accomplish what I'm trying to do? 完成我想做的最好的方法是什么? Is my database schema trash? 我的数据库架构是垃圾箱吗? Do I need a bunch of queries to get what I want done? 我需要一堆查询来完成我想做的事情吗? I'm not fluent in SQL :/ 我不太懂SQL:/

Thanks! 谢谢!

Gerard 杰拉德

your database schema is good and three queries are all right. 您的数据库架构很好,三个查询都可以。 Although you can use an API function instead of second query but it's doesn't really make any difference. 尽管您可以使用API​​函数代替第二个查询,但这并没有任何区别。 Note that you shouldn't select your question anyway, but special mysql function called LAST_INSERT_ID(); 请注意,您无论如何都不应该选择问题,而应使用名为LAST_INSERT_ID()的特殊mysql函数;

the only thing you forgot is a field to mark right answer/answer points or whatever of the kind 您唯一忘记的是标记正确答案/答案点或任何种类的字段

You first need to insert the question. 您首先需要插入问题。 Then you can use $questionId = mysql_insert_id(); 然后,您可以使用$questionId = mysql_insert_id(); , this gives you the generated id of the last insert. ,这将为您提供最后一次插入的生成ID。 Now you can use that to insert your answers properly. 现在,您可以使用它正确插入答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM