Wystąpił problem z modelowaniem schematu elektrycznego w SQL. Struktura, którą chciałbym uchwycić, to
part ←────────── pin
↑ ↑
part_inst ←───── pin_inst
gdzie „inst” jest skrótem od „instancja”.
Na przykład, mogę mieć jako partwzmacniacz pinoperacyjny LM358 z s 1OUT, 1IN-, 1IN +, GND, 2IN +, 2IN-, 2OUT i V CC . Mógłbym wtedy umieścić tę część na schemacie, tworząc a part_insti 8
pin_insts.
Ignorując pola danych, moją pierwszą próbą schematu było
create table parts (
part_id bigserial primary key
);
create table pins (
pin_id bigserial primary key,
part_id bigint not null references parts
);
create table part_insts (
part_inst_id bigserial primary key,
part_id bigint not null references parts
);
create table pin_insts (
pin_inst_id bigserial primary key,
part_inst_id bigint not null references part_insts,
pin_id bigint not null references pins
);
Głównym problemem związanym z tym schematem jest to, że pin_instmożna go powiązać part_instz, part_id=1ale pinma part_id=2.
Chciałbym uniknąć tego problemu na poziomie bazy danych niż na poziomie aplikacji. Zmodyfikowałem więc moje klucze podstawowe, aby to wymusić. Zmienione linie oznaczyłem za pomocą --.
create table parts (
part_id bigserial primary key
);
create table pins (
pin_id bigserial, --
part_id bigint not null references parts,
primary key (pin_id, part_id) --
);
create table part_insts (
part_inst_id bigserial, --
part_id bigint not null references parts,
primary key (part_inst_id, part_id) --
);
create table pin_insts (
pin_inst_id bigserial primary key,
part_inst_id bigint not null, --
pin_id bigint not null, --
part_id bigint not null references parts, --
foreign key (part_inst_id, part_id) references part_insts, --
foreign key (pin_id, part_id) references pins --
);
Wadę tej metody polega na tym, że zanieczyszcza ona klucze podstawowe: gdziekolwiek się odwołuję part_inst, muszę śledzić zarówno te, jak
part_inst_idi part_id. Czy istnieje inny sposób narzucenia ograniczenia
pin_inst.part_inst.part_id = pin_inst.pin.part_idbez nadmiernej gadatliwości?
pin_inst_idnadmiarowość. Możesz użyć tego(part_inst_id, part_id, pin_id)jako klucza podstawowego.