简体   繁体   English

如何删除表中的记录,该表的主键在另一个表中被引用为外键?

[英]How do I delete a record in a table which has a primary key referenced in another table as foreign key?

In my database, I have a table say "employee" which has a primary key attribute "employee_id" and another attribute "salary".在我的数据库中,我有一个表,上面写着“employee”,它有一个主键属性“employee_id”和另一个属性“salary”。 There is another table say "employee_qualification" which has a foreign key attribute "employee_id".还有一个表说“employee_qualification”,它有一个外键属性“employee_id”。 So, how can I delete all the records from "employee" and "employee_qualifications" with salary=10000?那么,如何从“employee”和“employee_qualifications”中删除salary=10000的所有记录?

This doesn't seem to work.这似乎不起作用。

DELETE FROM employee WHERE employee.salary=10000;

You can execute two statements.您可以执行两条语句。

DELETE FROM employee_qualifications WHERE employee_qualifications.employee_id in (SELECT employee_id FROM employee WHERE employee.salary=10000)
DELETE FROM employee WHERE employee.salary=10000

While this will work, it could leave some orphaned records in the employee_qualifications table.虽然这会起作用,但它可能会在employee_qualifications 表中留下一些孤立的记录。 The below option will clean the orphaned records.下面的选项将清除孤立的记录。

DELETE FROM employee WHERE employee.salary=10000
DELETE FROM employee_qualifications WHERE employee_qualifications.employee_id Not in (SELECT employee_id FROM employee)

MySQL allows deletes from multiple tables at the same time. MySQL 允许同时从多个表中删除。 So you can do:所以你可以这样做:

DELETE e, eq
    FROM employee e JOIN
         employee_qualitifications eq
    WHERE e.employee_id = eq.employee_id AND
          e.salary = 10000;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在PHP Script中插入已将前例键引用到另一个表的主键的记录? - How to insert record which has foregin key referenced to primary key of another table in PHP Script? 如何获得另一个表的外键引用的主键? - How do I get the primary key being referenced by a foreign key of another table? 如何将主键作为外键插入另一个表? - How do I insert the primary key to another table as foreign key? 如何将数据插入一个表并获取主键作为外键插入另一个表中? - How do I insert data into one table & get the primary key to insert in another table as a foreign key? 如何从具有主键自动增量的表中向具有外键的表中插入数据? - How can I insert data to a table which has a foreign key, from a table which has a primary key auto-increment? 更新一个表中的主键,这是另一表中的外键 - Update primary key in one table which is foreign key in another table 如何使用其他表中的外键删除具有主键的行? - How do I delete row with primary key using foreign key from other table? 如何检查是否每个主键值都被引用为另一个表中的外键 - How to check if every primary key value is being referenced as foreign key in another table 插入数据后,如何确保外键作为另一个表中的主键存在? - How do I ensure that a foreign key exists as a primary key in another table when data is inserted? 如何将一个表的主键值插入另一个表的外键列? - How do I insert primary key value from one table to foreign key column in another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM