我正在使用SQLite数据库连接在QT Creator中编写C ++应用程序。我想要实现的是,当我从表中删除一行时,其他引用它的表中的行也会被删除。所以在我的情况下,如果我从Basket中删除一行,则从计算机中引用行也会被删除,然后从子系统,订阅者,规则等中删除,直到结束。
这是我的数据库图表:
我为每个具有其他表的外键引用的表创建了触发器。
CREATE TRIGGER delete_fk BEFORE DELETE ON Basket
FOR EACH ROW BEGIN
DELETE FROM Computer WHERE computer.basket = old.id_basket;
END
CREATE TRIGGER delete_fk_comp BEFORE DELETE ON computer
FOR EACH ROW BEGIN
DELETE FROM subsystemtable WHERE subsystemtable.computer = id.id_computer;
END
CREATE TRIGGER delete_fk_subscriber_map BEFORE DELETE ON subscriber
FOR EACH ROW BEGIN
DELETE FROM mappingtable WHERE mappingtable.subscriber = old.id_subscriber;
END
CREATE TRIGGER delete_fk_subscriber_indirect BEFORE DELETE ON subscriber
FOR EACH ROW BEGIN
DELETE FROM indirectsubscriber WHERE indirectsubscriber.subscriber = old.id_subscriber;
END
CREATE TRIGGER delete_fk_subscriber BEFORE DELETE ON subscriber
FOR EACH ROW BEGIN
DELETE FROM reserve WHERE reserve.subscriber = old.id_subscriber;
END
CREATE TRIGGER delete_fk_subscriber_res BEFORE DELETE ON subscriber
FOR EACH ROW BEGIN
DELETE FROM reserve WHERE reserve.subscriber_res = old.id_subscriber;
END
CREATE TRIGGER delete_fk_subs BEFORE DELETE ON subsystem
FOR EACH ROW BEGIN
DELETE FROM subsystemtable WHERE subsystemtable.subsystem = old.id_subsystem;
END
CREATE TRIGGER delete_fk_substable_reg BEFORE DELETE ON subsystemtable
FOR EACH ROW BEGIN
DELETE FROM regulations WHERE regulations.subsystem = old.id;
END
CREATE TRIGGER delete_fk_substable BEFORE DELETE ON subsystemtable
FOR EACH ROW BEGIN
DELETE FROM subscriber WHERE subscriber.subsystem = old.id;
END
我得到了我想要的东西。它的工作原理与我想要的完全一样。但我现在的问题是性能低下。所以在我的数据库中,每个篮子大约有20台计算机,每台计算机大约有5个子系统,每个子系统有100个用户,等等。当我删除1个单篮时,整个过程大约需要400毫秒。我应该一次删除3个篮子,已经花了3秒多。
我需要找到一种方法让它更快地发挥作用。我想,限制在200-300毫秒左右。我需要任何关于如何做的建议。
答案 0 :(得分:2)
您正在手动实施外键。 这不是必要的;您可以使用ON DELETE actions让DB进行适当的更改。
无论是手动实现外键还是在数据库的帮助下,都需要创建indexes on certain key columns,否则查找相关行所需的所有查找都会很慢。