How can I do an UPDATE statement with JOIN in SQL Server?

前端 未结 16 1243
名媛妹妹
名媛妹妹 2020-11-21 11:51

I need to update this table in SQL Server with data from its \'parent\' table, see below:

Table: sale

id (int)
udid         


        
相关标签:
16条回答
  • 2020-11-21 12:03

    Teradata Aster offers another interesting way how to achieve the goal:

    MERGE INTO ud --what trable should be updated
    USING sale -- from what table/relation update info should be taken
    ON ud.id = sale.udid --join condition
    WHEN MATCHED THEN 
        UPDATE SET ud.assid = sale.assid; -- how to update
    
    0 讨论(0)
  • 2020-11-21 12:05

    The simplest way is to use the Common Table Expression (CTE) introduced in SQL 2005

    with cte as
    (select u.assid col1 ,s.assid col2 from ud u inner join sale s on u.id = s.udid)
    update cte set col1=col2
    
    0 讨论(0)
  • 2020-11-21 12:05

    Try this one, I think this will works for you

    update ud
    
    set ud.assid = sale.assid
    
    from ud 
    
    Inner join sale on ud.id = sale.udid
    
    where sale.udid is not null
    
    0 讨论(0)
  • 2020-11-21 12:06

    Simplified update query using JOIN-ing multiple tables.

       UPDATE
            first_table ft
            JOIN second_table st ON st.some_id = ft.some_id
            JOIN third_table tt  ON tt.some_id = st.some_id
            .....
        SET
            ft.some_column = some_value
        WHERE ft.some_column = 123456 AND st.some_column = 123456
    

    Note - first_table, second_table, third_table and some_column like 123456 are demo table names, column names and ids. Replace them with the valid names.

    0 讨论(0)
  • 2020-11-21 12:09

    Another example why SQL isn't really portable.

    For MySQL it would be:

    update ud, sale
    set ud.assid = sale.assid
    where sale.udid = ud.id;
    

    For more info read multiple table update: http://dev.mysql.com/doc/refman/5.0/en/update.html

    UPDATE [LOW_PRIORITY] [IGNORE] table_references
        SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
        [WHERE where_condition]
    
    0 讨论(0)
  • 2020-11-21 12:10

    This should work in SQL Server:

    update ud 
    set assid = sale.assid
    from sale
    where sale.udid = id
    
    0 讨论(0)
提交回复
热议问题