Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete when no other rows are using a relationship?

Tags:

mysql

I have a users table and an images table.

A user has only one image.

An image can belong to many users.

I'm trying to make it so that when a user is deleted, it's image is deleted but only if no other users are using that image.

I've tried to use on delete cascade but it only works the opposite way to what I'm trying to achieve - when you delete an image, the user is deleted.

Users:
id | name | image_id

Images:
id | url
like image 227
panthro Avatar asked Nov 23 '25 08:11

panthro


1 Answers

You can find the not used image with

  select  i.id, i.url  
  from  images i 
  left join  users u  on u.image_id = i.id
  where  image_id is null 

and delete

delete  i.* 
from  images i  
inner join  (

      select  i.id
      from  images i 
      left join  users u  on u.image_id = i.id
      where  image_id is null 
) t on t.id  = i.id 

if you have issue related to the fact that you are delete row that are involved in select then

delete  i.* 
from  images i  
inner join  ( 
  select  id 
  from ( 

      select  i.id
      from  images i 
      left join  users u  on u.image_id = i.id
      where  image_id is null  
  ) t1 
) t on t.id  = i.id 
like image 130
ScaisEdge Avatar answered Nov 28 '25 18:11

ScaisEdge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!