简体   繁体   English

删除最后一个匹配SQL上的记录

[英]delete record on last match SQL

I have 2 tables linked together as follows: 我有2个表链接在一起,如下所示:

Owner table | owner_id = Primary Key
Car table | car_id = Primary Key | owner_id = Foreign Key

Basically, every time a new car record is added, it is assigned to an owner. 基本上,每次添加新的汽车记录时,都会将其分配给所有者。 An owner can have multiple cars, but each car can only belong to one owner. 一个拥有者可以拥有多辆汽车,但是每辆汽车只能属于一个拥有者。

Is it possible to set a constraint or something that would delete the owner from the owner table on the last "matching" record. 是否可以设置约束或将在最后一个“匹配”记录上的所有者表中删除所有者的内容。

For instance, owner_1 owns 5 cars. 例如,owner_1拥有5辆汽车。 After the last car that they own is deleted, then it also drops the owner record from the database. 删除他们拥有的最后一辆汽车后,它还将从数据库中删除所有者记录。

I think an after delete trigger would do the job. 我认为删除后触发将完成这项工作。 Every time you delete a car record, you should query the same car table to see if there is another car with the same owner as the one you are deleting. 每次删除汽车记录时,都应查询同一汽车表,以查看是否有另一辆汽车与您要删除的汽车拥有相同的所有者。 something like this: 像这样的东西:

EDIT: Fixing Select Query :D 编辑:修复选择查询:D

DELIMITER $$
CREATE TRIGGER delete_owners_delete AFTER DELETE ON Car FOR EACH ROW
BEGIN
   DECLARE iCounter integer;
   SELECT COUNT(owner_id) INTO @iCounter FROM car c WHERE c.owner_id = old.owner_id;
   IF (@iCounter < 1) THEN
      DELETE FROM Owner WHERE owner_id = old.owner_id;
   END IF;
END; 
$$    

Hope it helps. 希望能帮助到你。 Cheers! 干杯!

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM