SQL Delete Rows Based on Another Table

前端 未结 6 1373
别那么骄傲
别那么骄傲 2020-12-13 18:44

This is probably very easy, but it\'s Monday morning. I have two tables:

Table1:

Field        | Type             | Null | Key | Default | Extra
id           


        
相关标签:
6条回答
  • 2020-12-13 18:52

    Something like this

    delete from table1 where group in (select group from table2)
    
    0 讨论(0)
  • 2020-12-13 18:56

    you can delete either table rows by using its alias in a simple join query like

    delete a from table1 a,table2 b where a.uid=b.id and b.id=57;
    

    here, you might specify either a or b to delete the corresponding table rows

    0 讨论(0)
  • 2020-12-13 18:58

    Off the top of my head:

    delete from Table1 where id in (select id from table1 inner join table2 on Table1.group = Table2.group)
    

    I did this a little differently than other posters -- I think if there is a large number of rows on Table2 this might be better. Can someone please set me straight on that?

    0 讨论(0)
  • 2020-12-13 19:00

    The nice solution is just writing the SQL as you say it yourself already:

    DELETE FROM Table1
    WHERE
      EXISTS(SELECT 1 FROM Table2 WHERE Table2.Group = Table1.Group)
    

    Regards, Arno Brinkman

    0 讨论(0)
  • 2020-12-13 19:06

    I think this is what you want:

    DELETE FROM `table1`
    WHERE `group` in (SELECT DISTINCT `group` FROM `table2`)
    
    0 讨论(0)
  • 2020-12-13 19:11

    I think this way is faster:

    DELETE FROM t1 USING table1 t1 INNER JOIN table2 t2 ON ( t1.group = t2.group );
    
    0 讨论(0)
提交回复
热议问题