简体   繁体   中英

How to delete records from two different tables that are linked with FK? SQL

I have two tables City and Buildings in my database. They are linked with city_number that is Primary Key in City table and Foreign Key in Buildings table. If user wants to delete record from City table I want to remove any records from the Buildings table that is tied to that City. I use unique auto incremented id passed through the argument to remove these records. My SQL Query looks like this:

DELETE C.*, B.*
FROM City AS C
    INNER JOIN Buildings AS B
        ON C.c_number = B.b_district
WHERE D.c_id = 'some id example: 107'; 

Query above won't work sicne SQL allow only records from one table to be removed with INNER JOIN so i will have to use two separate DELETE statements like this:

DELETE
FROM City 
WHERE c_id = '107'

DELETE 
FROM Buildings 
WHERE b_city = 'city that is tied to unique id 107' 

My question is, what is the best practice to remove records that are tied in two tables? Since I have to use two separate SQL statements, should I pass City and then delete record(s) from Buildings table? or Should I create another query that will pull City from City table based on unique id and then remove record(s) from Buildings? If anyone knows better way to do this please let me know.

I believe the easiest way to accomplish your goal would be to set up your foreign key with ON DELETE CASCADE. That way, whenever a row in the parent table is deleted, any related rows in the child table will be deleted automatically.

Here is an example of a way to alter a table in order to create a foreign key with ON DELETE CASCADE:

ALTER TABLE child_table
ADD CONSTRAINT fk_name
    FOREIGN KEY (child_col1, child_col2, ... child_col_n)
    REFERENCES parent_table (parent_col1, parent_col2, ... parent_col_n)
    ON DELETE CASCADE;

In your case, the child table would be Buildings and the parent table would be City. It sounds like you would have just city_number for the column. You'll have to fill in the name of your foreign key.

Like Shannon mentioned, you can use ON DELETE CASCADE to delete data from parent and child tables.

Here is a working example: http://sqlfiddle.com/#!18/f5860/10

Without writing out the code, here's what I would do:

  1. Select all the ids to be deleted for buildings belonging to a city
  2. Delete all the buildings
  3. Delete the city
  4. Put it in a stored procedure

Re-usable, self-contained, and clear.

This is a violation of SRP however, let me know if you care about that and I'll post a SRP based SQL solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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