我试图完成的是,当 tableB 中的一行被删除时,我想更新 tableA 中的行。
tableA的布局是这样的:
+----------------------------+--------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------------+--------------+------+-----+---------------------+----------------+
| user_id | int(11) | NO | PRI | NULL | auto_increment |
| nickname | varchar(32) | NO | | NULL | |
| password | varchar(129) | NO | | NULL | |
| mafia_id | int(11) | NO | | 0 | |
+----------------------------+--------------+------+-----+---------------------+----------------+
tableB 是这样的:
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| mafia_id | int(11) | NO | PRI | NULL | auto_increment |
| mafia_name | varchar(32) | NO | | | |
| mafia_tag | varchar(5) | NO | | | |
| mafia_color | int(11) | NO | | 0 | |
| mafia_car | int(11) | NO | | 0 | |
| mafia_base | int(11) | NO | | 0 | |
+-------------+-------------+------+-----+---------+----------------+
我想当tableB中对应的mafia_id被删除时,将所有tableA.mafia_id设置为0。
我在文档中读到,数据库会自动为您完成此操作,但您必须在创建表时指定一些内容(在 CREATE TABLE 中,create_definition: | CHECK (expr)?)。该文档对我来说有点不清楚。
我也读过这个主题: Create a trigger that updates a column on one table when a column in another table is updated
但这不适用于我,我想?
那么我如何创建这样的表(create table ...)或删除行语句? 提前致谢!
最佳答案
由于您使用的是 InnoDB,因此您可以通过 foreign key constraint 来实现此目的:
ALTER TABLE tableA
MODIFY mafia_id INT(11) NULL,
ADD FOREIGN KEY (mafia_id) REFERENCES tableB (mafia_id) ON DELETE SET NULL
如手册中所述:
SET NULL
: Delete or update the row from the parent table and set the foreign key column or columns in the child table toNULL
. This is valid only if the foreign key columns do not have theNOT NULL
qualifier specified. BothON DELETE SET NULL
andON UPDATE SET NULL
clauses are supported.If you specify a
SET NULL
action, make sure that you have not declared the columns in the child table asNOT NULL
.
请注意,该约束还有一个额外的优点,即确保 tableA
中的 mafia_id
值必须始终引用 tableB
中的现有记录。
关于mysql - 如何创建一个表,当内容更改时自动更新另一个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11812585/