我打算建立一个通知系统,向用户发送不同类型的消息(用户之间的私人消息,发布帖子的消息等)我正在寻找的是某种有条件的外键。 this_id
表格中的notification
列,以便它可以从表comments
或pm
中找到特定的行,我发现此 thread < / strong>这正是我想要的。所以我创建了一个“supertable”表,只有一列(SERIAL PRIMARY KEY
)由comments
和PM
引用。并且为了确保在任何新行插入comments
和PM
之前首先在supertable中插入新行以生成密钥,我设置了两个BEFORE INSERT INTO
触发器
CREATE TRIGGER `before_insert_comments`
BEFORE INSERT ON `comments`
FOR EACH ROW BEGIN
INSERT INTO supertable (this_id) VALUES ('')
END;
CREATE TRIGGER `before_insert_pm`
BEFORE INSERT ON `PM`
FOR EACH ROW BEGIN
INSERT INTO supertable (this_id) VALUES ('')
END;
但是当将记录插入表comments
或PM
时,我仍然会收到错误消息
Cannot add or update a child row: a foreign key constraint fails ( CONSTRAINT comments FOREIGN KEY (this_id) REFERENCES supertable (this_id) ON DELETE CASCADE ON UPDATE CASCADE)
。任何人都知道触发器的问题是什么?
表架构
CREATE TABLE notification (
id INT NOT NULL AUTO_INCREMENT,
this_id SERIAL PRIMARY KEY,
user_id INT,
is_read TINYINT,
FOREIGN KEY (this_id) REFERENCES supertable(this_id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
CREATE TABLE supertable (
this_id SERIAL PRIMARY KEY
);
CREATE TABLE comments (
this_id SERIAL PRIMARY KEY,
user_id INT ,
post TEXT,
is_approved TINYINT,
...
FOREIGN KEY (this_id) REFERENCES supertable(this_id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
CREATE TABLE PM (
this_id SERIAL PRIMARY KEY,
sender_id INT,
recipient_id INT ,
msg TEXT,
...
FOREIGN KEY (this_id) REFERENCES supertable(this_id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
答案 0 :(得分:0)
再次检查列映射。这里很少有关键点。
让我知道它是否有效。
CREATE TABLE supertable (
this_id SERIAL PRIMARY KEY
);
CREATE TABLE notification (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
this_foreign_id BIGINT UNSIGNED,
user_id INT,
is_read TINYINT,
FOREIGN KEY (this_foreign_id) REFERENCES supertable(this_id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
CREATE TABLE comments (
this_id SERIAL PRIMARY KEY,
user_id INT ,
post TEXT,
is_approved TINYINT,
FOREIGN KEY (this_id) REFERENCES supertable(this_id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
CREATE TABLE PM (
this_id SERIAL PRIMARY KEY,
sender_id INT,
recipient_id INT ,
msg TEXT,
FOREIGN KEY (this_id) REFERENCES supertable(this_id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
CREATE TRIGGER before_insert_comments
BEGIN
BEFORE INSERT ON comments
FOR EACH ROW BEGIN
INSERT INTO supertable (this_id) VALUES (NULL);
END;
CREATE TRIGGER before_insert_pm
BEGIN
BEFORE INSERT ON PM
FOR EACH ROW BEGIN
INSERT INTO supertable (this_id) VALUES (NULL);
END;