检查最新ID并添加1

时间:2015-12-29 15:53:45

标签: mysql database-design

由于我得到了几个应该包含很多问题的“项目”,我有一个问题页面,我填写视频链接,四个答案和四个下拉列表,用户可以为每个答案设置点数。 / p>

但是,在数据库中我有两个表。 当我填写并执行我的问题页面时,我已经做了所以每个答案都有一个id。在表“answer_det”中,正在设置Pid,Aid,answer和points。这就是它的样子:

enter image description here

当我插入第一个项目的第一个问题(Pid = 1)时的“问题”表:

enter image description here

我现在要做的是设置qid(question-id)。我不知道该怎么做,但我认为我应该有一个代码来检查pid的最大qid并加1,这样同一个项目的每个新问题都会得到一个新的qid。如果pid不在表中,那么qid应该得到值“1”。

因此,如果你看第一张图片,每个显示的行上的qid应为1,因为所有四个答案都属于同一个问题,这是pid = 1项目的第一个问题。因此,如果我想向同一个项目添加一个问题,它应该看起来相同,但qid = 2,依此类推。如果我然后为项目2添加新的(第一个)问题,则qid应该从1开始,依此类推。然后,如果我想为第一个项目再次添加一个新问题,代码应该检查最大qid是2,其中pid是1,然后插入一个带有答案但qid = 3的新问题。

它应该在表格“问题”上以相同的方式工作,您可以在第二张图片上看到。当第一个问题被创建时,我想第一个项目的第一个问题(pid = 1的那个)也有qid = 1和我填充的链接。 pid = 1的项目的第二个问题应该是qid = 2。如果我为新项目添加第一个问题,那么它应该是pid = 2和qid = 1。 这是我现在的代码,没有任何内容在两个表中都没有在qid中插入任何内容。

1 个答案:

答案 0 :(得分:0)

我想你有一组预定义的项目:

项目1>科学

项目2>数学

项目3>历史.....等等。

我建议你为具有projectID和projectName列的项目创建一个单独的表。

现在在您的问题页面中,将这些项目设置为下拉列表(选择选项)格式,其中projectID作为选项值,projectName作为下拉列表选择名称。

现在您有项目名称的选择选项,question_link的输入字段以及答案及其权重年龄的其他选择选项。现在,当您插入此表单(此问题)时,请尝试编写以下逻辑(我将尝试以伪代码方式编写)

//first check if this project already has questions in the question table.
 So do something like

SELECT* FROM question WHERE pid = $post['projectID'] ORDER BY qid DESC 
// or you could do SELECT TOP 1

// CASE1: if this project never had any questions, the select would return null. 
//Hence this is a first question for this project. Then simply write an insert query that 
//would insert $post['projectID'] to pid and 1 in qid (since this is the first question). 
//Also, insert a series of rows in the answer_det table that will have $post['projectID'] 
//to pid and 1 for qid and the answer and points as submitted.


// CASE2: if this project already has 1 or more questions, your select query from above 
//will return some rows and if you pick $row[0]['qid'], this would be the highest number 
//value for question (qid) as we selected using  ORDER BY qid DESC. Now, simply do inserts 
//in both the tables like you would do as above but this time, in the qid field in both 
//the tables, instead of inserting 1, you would insert qid => $row[0]['qid'] + 1.
//You wouldn't need to know what the qid was, all you need is to get the last qid and add 
//1 to it.

//Also, you can create a separate page to add the projectName as you feel to add new
//projects and insert this into the project_table and this will begin to show up in the
//select options when you are adding new questions.