Creating foreign key on same table SQLite

会有一股神秘感。 提交于 2019-12-10 14:50:05

问题


Recently I started using SQLite (as required for my study) and I came accross a couple of restrictions of SQLite and I was wondering: can't SQLite create foreign keys on the same table? E.g. this is my code:

CREATE TABLE Categories
(
    name varchar(20),
    parent_category varchar(20) NULL,
    PRIMARY KEY(name),
    FOREIGN KEY parent_category_fk(parent_category) REFERENCES Categories(name)
)

But it gives me an error for the foreign key when I try to execute the SQL in SQLiteStudio.

Does anyone know why this isn't working?


回答1:


The problem is that you have the wrong syntax for the FK clause. It should be:

FOREIGN KEY (parent_category) REFERENCES Categories(name)

If you want to name the FK constraint, you do that with a prefix of the CONSTRAINT keyword, like this:

CONSTRAINT parent_category_fk FOREIGN KEY (parent_category) REFERENCES Categories(name)


来源:https://stackoverflow.com/questions/15967146/creating-foreign-key-on-same-table-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!