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

后端 未结 3 1752
一个人的身影
一个人的身影 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
    
    0 讨论(0)
  • 2021-02-04 06:24

    Assuming your first table is named customers and those customers without a salesperson have an s_id of NULL

    UPDATE invoices JOIN customers USING (c_id)
    SET invoices.s_id = customers.s_id, invoices.s_name = customers.s_name
    WHERE customers.s_id IS NOT NULL;
    

    I suggest testing in development or running a SELECT query using the JOIN above first to ensure the results.

    0 讨论(0)
  • 2021-02-04 06:45

    You can create a view to make your UPDATE statement simple. The view should contain your query (in your case the query that associates customers and salespeople). Then update your table (invoices in your case) like this:

    update TableToUpdate ttu, MyView mv
    set ttu.column = mv.column
    where ttu.key = mv.key
    
    0 讨论(0)
提交回复
热议问题