以下是更规范的方法。这有利于存储所有问题共有的一组单独的选项。
CREATE TABLE choices (
choice_id integer primary key autoincrement,
choice string not null
);
CREATE TABLE questions (
ques_id integer primary key autoincrement,
ques string not null,
choice_id integer,
FOREIGN KEY(choice_id) REFERENCES choice(choice_id)
);
示例解释器会话:
>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute("""CREATE TABLE choices (
... choice_id integer primary key autoincrement,
... choice string not null
... );""")
<sqlite3.Cursor object at 0x7f29f60b8ce8>
>>> c.execute("""CREATE TABLE questions (
... ques_id integer primary key autoincrement,
... ques string not null,
... choice_id integer,
... pub_date integer,
... FOREIGN KEY(choice_id) REFERENCES choice(choice_id)
... );""")
<sqlite3.Cursor object at 0x7f29f60b8ce8>
>>> c.execute("INSERT INTO choices (choice) VALUES ('yes')")
<sqlite3.Cursor object at 0x7f29f60b8ce8>
>>> c.execute("""INSERT INTO questions (ques,choice_id)
VALUES ('do you like sqlite?',1)""")
<sqlite3.Cursor object at 0x7f29f60b8ce8>
>>> c.execute("""SELECT ques, choice
FROM questions q
JOIN choices c ON c.choice_id = q.choice_id;""")
>>> c.fetchall()
[(u'do you like sqlite?', u'yes')]