简体   繁体   中英

MySql Update one table from another fails

I was trying to update one table from another table and the query set all of the fields,customers.entry_company_tax_id, to "NULL" which did not make sense to me.

here is the query, can someone tell me what I did wrong ?

UPDATE customers 
    SET customers.entry_company_tax_id = (
        SELECT prospects.account
        FROM prospects
        WHERE prospects.prospect  = customers.entry_company_tax_id 
    );

They would be set to NULL if there are no matches.

I would start by using JOIN syntax for the update:

UPDATE customers c JOIN
       prospects p
       ON p.prospect = c.entry_company_tax_id
    SET c.entry_company_tax_id = p.account;

This has the advantage that it will only update matching records -- so no new NULL values (unless p.account is NULL ).

Then, you can investigate if that is the right JOIN key for the two tables. Are you use entry_company_tax_id is used both for the JOIN and for the field value?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM