SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Dec 2007
    Posts
    36
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Updating 2 tables in one query when similar data does not exist in both

    I'm trying to update multiple tables in a single query, but what I'm using does not seem to do any updating.

    Code:
     
    UPDATE table1,table2 SET table1.name='John Doe',table2.name='John Doe' WHERE table1.id=1 and table2.id = 1;
    Problem is, a row with the same id may not be present in both tables. How can I do an update in a case like this?

    In this case, the `id 1` is present in table1, but not in table2.

    The idea is to update data in both tables, even if an id does not exist in table1 or table2

    How do I write the sql for something like this?

    Example:

    Code:
        id is present in table1 but not in table2 -> Update table1. 
    
        id is present in table2 but not table1 -> update table2. 
    
        id is present in both table1 and table2 update both.
    
        id is not present in either tables -> do nothing

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,246
    Mentioned
    59 Post(s)
    Tagged
    3 Thread(s)
    just use two update statements

    why the need for one?
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •