Implement/use foreign keys in SQLite?

2019-07-29 13:11发布

How can I implement a foreign key in SQLite? I was thinking something like this:

CREATE TABLE job (_id INTEGER PRIMARY KEY AUTOINCREMENT, employer_id INTEGER, ...);
CREATE TABLE employer(_id INTEGER, employer_name TEXT NOT NULL, ...);

Where employer_id is the _id from the table employer. Would this work? Is there another fast, maybe less prone to error way? Maybe with triggers?

2条回答
男人必须洒脱
2楼-- · 2019-07-29 14:02

See SQLite (3.6.19) Foreign Key Support

(Earlier version of SQLite do not support enforced FK relationships.)

查看更多
放荡不羁爱自由
3楼-- · 2019-07-29 14:06

Maybe I don't understand the question, but if it's the constraint you want, just do this:

ALTER TABLE Job
  ADD FOREIGN KEY (employer_id)
    REFERENCES Employer(_id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION;
查看更多
登录 后发表回答