-4

In SQLite, if a foreign key refers to multiple tables, how can we create a table and insert values? Trying to insert values I got a "foreign key constraint failed" message:

CREATE TABLE ClientPhone
(
    phone   VARCHAR(10),
    clientID    INTEGER,              
    
Primary Key (phone),
Foreign key (clientID) REFERENCES CompanyClient(clientID) on update cascade on delete cascade,
Foreign key (clientID) REFERENCES PersonalClient(clientID) on update cascade on delete cascade 
);

INSERT INTO ClientPhone VALUES(0402563698,101234);
INSERT INTO ClientPhone VALUES(0427841235,102356);
INSERT INTO ClientPhone VALUES(0465123002,107845);
INSERT INTO ClientPhone VALUES(0401258741,109632);

enter image description here

user4157124
  • 2,809
  • 13
  • 27
  • 42
Kushani5j
  • 73
  • 1
  • 1
  • 8
  • Debug questions require a [mre]. 1 FK can reference 1 table, so what are you trying to say? Better try to say what constraint/restriction/limitation you want to hold without (mis)using the term "FK". PS This will be a faq. [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/q/261592/3404097) [ask] [Help] – philipxy Nov 02 '22 at 05:05
  • [Why should I not upload images of code/data/errors when asking a question?](https://meta.stackoverflow.com/q/285551/3404097) – philipxy Nov 02 '22 at 05:05
  • 1
    *... if a foreign key refers to multiple tables...* A foreign key should reference 1 table. – forpas Nov 02 '22 at 08:31

1 Answers1

1

You can disable foreign keys before insertions:

PRAGMA foreign_keys=0;

Even if SQLite allows this ddl, this is a bad idea. You should reverse fk directions. Also, see this Foreign key referring to primary keys across multiple tables?

PChemGuy
  • 1,582
  • 3
  • 6
  • 18