在MySQL中使用外键工作的问题

时间:2010-04-13 22:57:58

标签: sql mysql foreign-keys innodb foreign-key-relationship

我一直试图删除级联,但它似乎无法正常工作。我确定我遗漏了一些显而易见的东西,任何人都可以帮我找到它吗?

我希望'articles'表上的删除会触发'article_section_lt'表中相应行的删除。

CREATE TABLE articles (
    id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    url_stub VARCHAR(255) NOT NULL UNIQUE,
    h1 VARCHAR(60) NOT NULL UNIQUE,
    title VARCHAR(60) NOT NULL,
    description VARCHAR(150) NOT NULL,
    summary VARCHAR(150) NOT NULL DEFAULT "",
    html_content TEXT,
    date DATE NOT NULL,
    updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)ENGINE=INNODB;


CREATE TABLE article_sections (
    /* blog, news etc */
    id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    url_stub VARCHAR(255) NOT NULL UNIQUE,
    h1 VARCHAR(60) NOT NULL,
    title VARCHAR(60) NOT NULL,
    description VARCHAR(150) NOT NULL,
    summary VARCHAR(150) NOT NULL DEFAULT "",
    html_content TEXT NOT NULL DEFAULT ""
)ENGINE=INNODB;

CREATE TABLE article_section_lt (
    fk_article_id INTEGER UNSIGNED NOT NULL REFERENCES articles(id) ON DELETE CASCADE,
    fk_article_section_id INTEGER UNSIGNED NOT NULL
)ENGINE=INNODB;

1 个答案:

答案 0 :(得分:3)

您需要显式声明外键约束。列定义中的REFERENCES子句不起作用。

试试这个:

CREATE TABLE article_section_lt (
    fk_article_id INTEGER UNSIGNED NOT NULL,
    fk_article_section_id INTEGER UNSIGNED NOT NULL,
    KEY fk_article_id (fk_article_id),
    CONSTRAINT fk_article_section_lt_to_article FOREIGN KEY (fk_article_id) REFERENCES articles(id) ON DELETE CASCADE
)ENGINE=INNODB;