简体   繁体   中英

update row check duplicates

I hope you can help me with the correct SQL syntax.

main_accounts (table1)
'---id, group_name, account_name, payment_method

payments (table2)
'---id, account_name, payment_method

What I am trying to do is to update the account_name row in payments where payment_method is equal to payment_method in main_accounts table.

I tried:

update payments 
set account_name = (select account_name 
                    from main_accounts 
                    where payment_method = payment_method) 
WHERE payment_method = payment_method

but it's saying:

#1242 - Subquery returns more than 1 row

So I don't know... I wish I could do this:

update payments 
set account_name = (select account_name 
                    from main_accounts 
                    where payment_method = **{is equal to payment_method in main_accounts table}**

Additionally, I wish I could make this as a trigger that when main_accounts table is updated, account_name goes automatically to payments table where the account_name is printed to the column when payment_method matches the payment_method in main_accounts .

You are getting that error, cause your subquery is returning more than 1 value which can't be used in SET statement. You should do a JOIN with other table in question while performing the UPDATE statement. Something like

UPDATE payments a 
    JOIN main_accounts b ON a.payment_method = b.payment_method        
SET a.account_name = b.account_name;

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