Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete rows in MySQL matching two columns in another table

Tags:

sql

mysql

I am using MySQL and would like to delete entries from table T1:

user_id  level_id  other_data
   1        5         ...
   2        7         ...
   :

where the user_id and level_id values appear together in table T2:

user_id  level_id
   1         5
   2         6

In this example, the first row would be deleted from table T1.

I tried:

delete from T1 where (user_id,level_id) in select user_id,level_id from T2;

but that has a syntax error.

like image 332
Ellen Spertus Avatar asked Oct 28 '25 06:10

Ellen Spertus


1 Answers

You are pretty close. Try using exists:

delete from T1
    where exists (select 1
                  from t2
                  where t1.user_id = t2.user_id and t1.level_id = t2.level_id
                 );
like image 62
Gordon Linoff Avatar answered Oct 29 '25 21:10

Gordon Linoff



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!