MySQL: Update all rows in a table matching results of another query

后端 未结 3 1746
一个人的身影
一个人的身影 2021-02-04 05:56

I\'ve written a query returning rows associating Customers and Salespeoeple.

Note that the query joins several database tables. And note that not all c

3条回答
  •  不知归路
    2021-02-04 06:19

    Using subqueries

    Most widely supported option

    UPDATE INVOICES
       SET s_id = (SELECT cs.s_id
                     FROM CUSTOMERS_AND_SALES cs
                    WHERE cs.c_id = INVOICES.c_id),
           s_name = (SELECT cs.s_name
                       FROM CUSTOMERS_AND_SALES cs
                      WHERE cs.c_id = INVOICES.c_id)
     WHERE INVOICES.c_id IN (SELECT cs.s_id
                               FROM CUSTOMERS_AND_SALES cs)
    

    Using JOINs

    UPDATE INVOICES
      JOIN CUSTOMERS_AND_SALES cs ON cs.c_id = INVOICES.c_id
       SET s_id = cs.s_id,
           s_name = cs.s_name
    

提交回复
热议问题