delete query from two tables

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • KingKong07
    New Member
    • Apr 2007
    • 6

    delete query from two tables

    Hi

    I need some help on a query. I need to delete some records from a table, this table has a dependency to another table

    Table 1: dbo.Accounts and Table 2: dbo.AccountsToU ser

    In the dbo.Accounts table there are

    AccountId and OwnedByAccountI d


    54708002 54708001
    54708003 54708001
    65708002 65708001
    65708003 65708001
    54708001 22334401
    65708001 NULL


    In the dbo.AccountsToU ser there are

    AccountId and UserId

    65708002 100
    65708003 101
    65708003 104
    65708003 106
    54708001 194
    65708002 199


    What I need is to delete every record from dbo.AccountsToU ser that has an account connection to an account in the dbo.Accounts that has OwnedByAccount like NULL

    So in the example above I should delete from dbo.AccountsToU ser

    65708002 100
    65708003 101
    65708003 104
    65708003 106



    Since they are connected to 65708001 which has OwnedByAccountS tatus like NULL

    I could delete the records manually since the table isn’t that big, but I need this to be a daily job so all help would be very nice :)

    Thanks!
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    When deleting from a table (table1) that requires a JOIN (table2) there
    are about three methods, all not very intuititive.
    But I prefer this
    Code:
    DELETE table1,table2 FROM table1 JOIN table2
    WHERE condition

    Comment

    • deepuv04
      Recognized Expert New Member
      • Nov 2007
      • 227

      #3
      HI,
      Try the following query
      [code=sql]
      DELETE FROM AccountsToUser
      FROM AccountsToUser AS AU INNER JOIN
      Accounts as A ON a.AccountId = au.AccountId
      WHERE a.OwnedByAccoun tId in (select AccountId from Accounts where OwnedByAccountI d is null)
      [/code]
      thanks

      Comment

      Working...