两种一对多关系与三张表

1 投票
1 回答
585 浏览
提问于 2025-04-16 16:13
import sqlite3

# get connection and cursor objects
conn = sqlite3.connect('iodatabase.sdb')
c = conn.cursor()

# create tables
c.execute('''create table grand_parent (
    id integer primary key autoincrement,
    name text
)''')


c.execute('''create table parent (
    id integer primary key autoincrement,
    name text
    grand_parent_id text,
    FOREIGN KEY(grand_parent_id) REFERENCES grand_parent(name)
)''')

c.execute('''create table child (
    id integer primary key autoincrement,
    name text,
    module text,
    type text,
    desc text,
    parent_id text,
    FOREIGN KEY(parent_id) REFERENCES parent(name)
)''')

c.execute("INSERT INTO grand_parent VALUES(null, 'AS1')")

c.execute("INSERT INTO parent VALUES(null, 'Parent1', 'AS1')")
c.execute("INSERT INTO child VALUES(null, 'Child1', 'AO', 'CVXY', '1', 'Parent1', 'AS1')")
c.execute("INSERT INTO child VALUES(null, 'Child2', 'AO', 'CVXY', '1', 'Parent1', 'AS1')"
c.execute("INSERT INTO child VALUES(null, 'Child3', 'AI', 'FTRE', '1', 'Parent1', 'AS1')"
c.execute("INSERT INTO child VALUES(null, 'Child4', 'AI', 'FTRE', '1', 'Parent1', 'AS1')")

c.execute("INSERT INTO parent VALUES(null, 'Parent2', 'AS1')")
c.execute("INSERT INTO child VALUES(null, 'Child1', 'AO', 'CVXY', '1', 'Parent2', 'AS1')")
c.execute("INSERT INTO child VALUES(null, 'Child6', 'AI', 'FTRE', '1', 'Parent2', 'AS1')")
c.execute("INSERT INTO child VALUES(null, 'Child4', 'BO', 'MESR', '1', 'Parent2', 'AS1')")

大家好,

我有三个表格。一个是祖父母表,一个是父母表,最后一个是孩子表。我的意思是,我希望孩子的数据知道它属于哪个父母和祖父母。同时,我也希望父母的数据知道它属于哪个祖父母。我尝试自己做,但没有成功。我该如何设置这些表格之间的关系呢?表格的结构应该是什么样的?

提前谢谢大家。

编辑

忽略代码。只需用原始SQL设置三个表格,以满足所需的关系。这是我第一次做这样的事情,我需要一些指导。

1 个回答

2

如果我理解得没错:

问题出在这里:FOREIGN KEY(parent_id) REFERENCES parent(name),应该改成FOREIGN KEY(parent_id) REFERENCES parent(id)。也就是说,要用ID来做引用,而不是用名字。

通过查询父表,你可以从子表中返回祖父记录。

如果这不是你想要的,请留言告诉我。

撰写回答