父子关系中的条件删除

时间:2019-04-07 07:52:55

标签: sql join sqlite database-trigger cascading-deletes

我有4张桌子:

tc_topic_table(tc_topic_id,tc_topic_area)
tc_keywords_table(tc_keyword_id,tc_keyword,topic_id,
foreign key(topic_id) refrences tc_topic_table(tc_topic_id) ON DELETE CASCADE)
m_twitterUser(id,location,verified)
tc_master_table(m_id,m_text,m_keyword_id,author_id, foreign key(m_keyword_id) refrences tc_keywords_table(tc_keyword_id)ON DELETE CASCADE ,
foreign key (author_id)refrences user(id) ON DELETE RESTRICT)

在删除主题时,需要删除所有关键字,主表中的行以及与主用户相关的用户。 ON DELETE CASCADE可以帮助我执行此操作,但由于它是tc_master_table的父表,因此无法帮助我删除m_twitterUser。
可能有些用户在两个主题和多个关键字上花了点时间。如果我尝试删除,那么FOREIGN KEY将会失败,但是我想离开它们,并在用户未发布任何主题的地方删除,而不是我要删除的

在删除tc_master_table之前或之后,我尝试过从m_twitterUser中删除的触发器,但是它给了我FOREIGN KEY Constraint FAILED。

我正在与PRAGMA foreign_keys=ON;

一起使用

tc_topic_table:

CREATE TABLE "tc_topic_table" ( `tc_topic_id` INTEGER PRIMARY KEY     AUTOINCREMENT, `tc_topic_area` TEXT NOT NULL)

tc_keywords_table:

CREATE TABLE "tc_keywords_table" ( `tc_keyword_id` INTEGER PRIMARY KEY AUTOINCREMENT, `tc_keyword` TEXT NOT NULL, `topic_id` INTEGER NOT NULL, `sentiment` NUMERIC, title text, FOREIGN KEY(`topic_id`) REFERENCES `tc_topic_table`(`tc_topic_id`) ON DELETE CASCADE)

m_twitterUser:

CREATE TABLE `m_twitterUser` ( `id` INTEGER UNIQUE, `location` TEXT, `verified` TEXT, PRIMARY KEY(`id`) )

tc_master_table:

CREATE TABLE "tc_master_table" ( `m_tweet_id` INTEGER UNIQUE, `m_keyword_id` INTEGER, `m_text` TEXT, `m_created_at` NUMERIC, `m_rt_count` INTEGER, `m_fav_count` INTEGER, `lang` TEXT, `m_sent_val` REAL DEFAULT 0, `author_id` INTEGER, PRIMARY KEY(`m_tweet_id`), FOREIGN KEY(`m_keyword_id`) REFERENCES `tc_keywords_table`(`tc_keyword_id`), FOREIGN KEY(`author_id`) REFERENCES `m_twitterUser`(`id`), ON DELETE RESTRICT)

触发器:

create trigger remove_user
before delete ON tc_master_table
BEGIN
delete from m_twitterUser where id=old.author_id;
END;
create trigger remove_user
after delete ON tc_master_table
BEGIN
delete from m_twitterUser where id=old.author_id;
END; 

我正在绑:

delete from tc_topic_table where tc_topic_id=24;
Output:
Error: FOREIGN KEY constraint failed

我想让所有留在主表中的数据留在表中的用户,如果没有留下他们的数据,则删除

1 个答案:

答案 0 :(得分:0)

另一个对我有帮助的触发器

create trigger remove_user
after delete ON tc_topic_table
begin
DELETE from m_twitterUser where id in(
select id
FROM m_twitteruser as usr
        INNER JOIN tc_master_table as mstr
ON usr.id=mstr.author_id
        INNER JOIN tc_keywords_table as key
ON key.tc_keyword_id=mstr.m_keyword_id
        INNER JOIN tc_topic_table as topic
ON topic.tc_topic_id=key.topic_id
        WHERE topic.tc_topic_id=old.tc_topic_id);
end;