有SQL表:
问题<表类>q_id (PK) userID(颗用户(userID)) 问题 tbody><<tr>1 111 "1和4之间是什么?"> 2222 "5和7之间是什么?"> 表类>
cursor.execute("SELECT answer.answer, question.question FROM answer Left JOIN question on answer.q_id=question.q_id WHERE question.user_id = (%s)", userID)
result = cursor.fetchall()
question_list = []
my_questions = {}
for answer in result:
if answer[1] in my_questions.keys():
my_questions[answer[1]]['answers'].append(answer[0])
else:
my_questions[answer[1]] = MyQuestion(answer[1], [answer[0]])
question_list = my_questions.value()
使用连接查询查询后,使用问题字符串作为键将结果组织到字典中。也可以是q_id
对于查询中的每一行,如果问题已经作为键存在,转到value MyQuestion对象并将答案附加到MyQuestion['answer']。否则,将问题作为键添加到新的MyQuestion对象中。
返回MyQuestions列表的my_questions字典的值。