我在使用外键从父表中重新获取值时遇到了问题。
我正在使用两张桌子,
1)问题表
2)答案表
在问题表字段中,questionId
,question
和requiredTime
。
在答案表字段中,answerId
,answer
和questionId
(从问题表中引用的外键)
我的问题是, 在问题表中如何获取questionId的值并插入Answer表?
对于一个问题有4个答案意味着4个选项按照问题。
//Create Table Question
public static final String CREATE_QUESTION = "CREATE TABLE IF NOT EXISTS "
+ TABLE_QUESTION
+ " ( "
+ KEY_QUESTION_ID
+ " INTEGER primary key not null , "
+ KEY_QUESTION
+ " text not null , "
+ KEY_TIME_REQUIRED + " text " + ");";
//Create Table Answer
public static final String CREATE_ANSWER = "CREATE TABLE IF NOT EXISTS "
+ TABLE_ANSWER
+ " ( "
+ KEY_ANSWER_ID
+ " INTEGER primary key not null , "
+ KEY_ANSWER
+ " text , "
+ KEY_QUESTION_ID
+ " INTEGER ,"
+ " FOREIGN KEY (" + KEY_QUESTION_ID + ") REFERENCES " + TABLE_QUESTION + " (" + KEY_QUESTION_ID + "));";
In Code,
for (int i = 0; i < arr_question_id.size(); i++) {
item_bean.setTimeRequired(arr_time_required.get(i));
item_bean.setQuestionId(arr_question_id.get(i));
item_bean.setQuestion(arr_question.get(i));
dbAdapter.openForWrite();
dbAdapter.insertQuestion(Integer.parseInt(arr_question_id.get(i)), arr_question.get(i), arr_time_required.get(i));
dbAdapter.close();
}
for (int j = 0; j < arr_answer_id.size(); j++) {
item_bean.setAnswerId(arr_answer_id.get(j));
item_bean.setAnswer(arr_answer.get(j));
item_bean.setCorrect(arr_correct.get(j));
System.out.println("!!!!!!!!!!1 Integer.parseInt(arr_question_id.get(j)=====" + json_object_question.getString("questionID"));
dbAdapter.openForWrite();
dbAdapter.insertAnswer(Integer.parseInt(arr_answer_id.get(j)), arr_answer.get(j), Integer.parseInt(json_object_question.getString("questionID")));
dbAdapter.close();
}
Problem with below Line,
dbAdapter.insertAnswer(Integer.parseInt(arr_answer_id.get(j)), arr_answer.get(j), Integer.parseInt(json_object_question.getString("questionID")));
For Question Id,For one Question loop repeat 4 times.
Table Question
***************
questionId question timeRequired
1 What is your Name? 10
2 What is your pets Name? 10
3 What is your native? 10
etc.
Table Answer
***********
answerId answer questionId
101 Neha 1
102 Sneha 1
103 Meeta 1
104 Mamata 1
105 Meetu 2
106 Keenu 2
107 Teenu 2
108 Nehu 2
etc.
我无法为Table Answer获取questionId的值。 请帮我。 我在等你的回复和你的建议。 请建议我。 谢谢。 里纳
答案 0 :(得分:0)
你几乎已经完成了所有事情,只需要从你的答案表中选择你想要的问题ID:
SQLiteDatabase db = this.getWritableDatabase();
String[] columns = new String[] { "answer" }
String where = KEY_QUESTION_ID + " = ?";
String[] whereArgs = new String[] { questionId + "" };
Cursor c = db.query(
TABLE_ANSWER /* table */,
columns /* columns */,
where /* where or selection */,
whereArgs /* selectionArgs i.e. value to replace ? */,
null /* groupBy */,
null /* having */,
null /* orderBy */
);
答案 1 :(得分:0)
您可以使用联接或创建视图获得所需的结果。这取决于你的需要。 http://www.tutorialspoint.com/sqlite/sqlite_using_joins.htm
你应该保留外键约束,否则没有意义,如果没有问题你会回答为什么?