SQL update query using joins

后端 未结 11 1826
天涯浪人
天涯浪人 2020-11-22 01:15

I have to update a field with a value which is returned by a join of 3 tables.

Example:

select
    im.itemid
    ,im.sku as iSku
    ,gm.SKU as GSKU         


        
相关标签:
11条回答
  • 2020-11-22 01:47

    Adapting this to MySQL -- there is no FROM clause in UPDATE, but this works:

    UPDATE
        item_master im
        JOIN
        group_master gm ON im.sku=gm.sku 
        JOIN
        Manufacturer_Master mm ON gm.ManufacturerID=mm.ManufacturerID
    SET
        im.mf_item_number = gm.SKU --etc
    WHERE
        im.mf_item_number like 'STA%'
        AND
        gm.manufacturerID=34
    
    0 讨论(0)
  • 2020-11-22 01:51

    It is very simple to update using join query in SQL .You can do it without using FROM clause. Here is an example :

        UPDATE customer_table c 
    
          JOIN  
              employee_table e
              ON c.city_id = e.city_id  
          JOIN 
              anyother_ table a
              ON a.someID = e.someID
    
        SET c.active = "Yes"
    
        WHERE c.city = "New york";
    
    0 讨论(0)
  • 2020-11-22 01:54

    One of the easiest way is to use a common table expression (since you're already on SQL 2005):

    with cte as (
    select
        im.itemid
        ,im.sku as iSku
        ,gm.SKU as GSKU
        ,mm.ManufacturerId as ManuId
        ,mm.ManufacturerName
        ,im.mf_item_number
        ,mm.ManufacturerID
        , <your other field>
    from 
        item_master im, group_master gm, Manufacturer_Master mm 
    where
        im.mf_item_number like 'STA%'
        and im.sku=gm.sku
        and gm.ManufacturerID = mm.ManufacturerID
        and gm.manufacturerID=34)
    update cte set mf_item_number = <your other field>
    

    The query execution engine will figure out on its own how to update the record.

    0 讨论(0)
  • 2020-11-22 01:54

    Try like this...

    Update t1.Column1 = value 
    from tbltemp as t1 
    inner join tblUser as t2 on t2.ID = t1.UserID 
    where t1.[column1]=value and t2.[Column1] = value;
    
    0 讨论(0)
  • 2020-11-22 01:56

    Let me just add a warning to all the existing answers:

    When using the SELECT ... FROM syntax, you should keep in mind that it is proprietary syntax for T-SQL and is non-deterministic. The worst part is, that you get no warning or error, it just executes smoothly.

    Full explanation with example is in the documentation:

    Use caution when specifying the FROM clause to provide the criteria for the update operation. The results of an UPDATE statement are undefined if the statement includes a FROM clause that is not specified in such a way that only one value is available for each column occurrence that is updated, that is if the UPDATE statement is not deterministic.

    0 讨论(0)
提交回复
热议问题