简体   繁体   中英

PostgreSQL: Delete a row and all of it's references (FK) existing in others tables?


Let's say i have a table named "users" like this:

+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
| 1  | 'Sid'      | 'Barrett' |
| 2  | 'Roger'    | 'Waters'  |
| 3  | 'Richard'  | 'Wright'  |
| 4  | 'David'    | 'Gilmour' |
| 5  | 'Nick'     | 'Mason'   |
+----+------------+-----------+

Each "user" have lots of references on several tables with the same column name "user_id" as a FK.
If i need to delete an element i believe the procedure is to delete the relations first (to avoid the "violates foreign key constraint" error) and then the element itself in "users" table, right?

But... Is there any possibility to delete a "user" element with all its references on all the others tables?
I'm working with NodeJS (Express) and using PostgreSQL. Please apologize if the answer is obvious, I'm a newbie in SQL.

Thanks a lot in advise!!

Yes, use on delete cascade on the foreign keys.

create table users (
  id bigserial primary key
  ...
);

create table posts (
  ...
  user_id bigint not null references users on delete cascade
  ...
)

Now when a user is deleted, all their associated posts will also be deleted.

This will go on, for example, if a post has comments...

create table comments (
  ...
  post_id biging not null references posts on delete cascade
  ...
)

When a user is deleted their posts will be deleted, and those posts' comments will be deleted. That's the "cascade" part.

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