我想在数据库中表示植物及其属/种。这是我想到的模式:
CREATE TABLE genuses (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE NOT NULL);
CREATE TABLE species (
id INTEGER PRIMARY KEY,
genus_id INTEGER NOT NULL REFERENCES genuses(id),
name TEXT UNIQUE NOT NULL);
CREATE TABLE plants (
id INTEGER PRIMARY KEY,
species_id INTEGER NOT NULL REFERENCES species(id),
...);
这种方法的问题在于,它不允许植物有一个没有特定物种的属。例如,我拥有蝴蝶兰兰花。我知道该属是蝴蝶兰,但我无法识别确切的物种。
我能想到两种解决方案,但我都不满意:
有更好的方法吗?
复合键对于强制 genuses
和
plants
之间的传递关系非常有用。
你可以这样做:
CREATE TABLE genuses (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE NOT NULL
);
CREATE TABLE species (
id INTEGER not null,
genus_id INTEGER NOT NULL REFERENCES genuses (id),
PRIMARY KEY (id, genus_id),
name TEXT UNIQUE NOT NULL
);
CREATE TABLE plants (
id INTEGER PRIMARY KEY,
genus_id INTEGER NOT NULL REFERENCES genuses (id),
species_id INTEGER,
FOREIGN KEY (species_id, genus_id) REFERENCES species (id, genus_id),
name VARCHAR(50)
);
然后您可以插入:
insert into genuses (id, name) values (100, 'G1');
insert into genuses (id, name) values (101, 'G2');
insert into species (id, genus_id, name) values (1000, 100, 'S1');
insert into species (id, genus_id, name) values (1001, 100, 'S2');
insert into plants (id, genus_id, species_id, name) values (200, 100, 1000, 'P1');
insert into plants (id, genus_id, species_id, name) values (201, 100, null, 'P2');
请参阅db-Fiddle的运行示例。