简体   繁体   中英

SQL query for update/replace updating too many records

I am a SQL novice and was "nominated" to work on a project to update some account settings for customers.
Basically I need to replace a setting ("OLDACCESS") with a "NEWACCESS" on a user_settings table. However, I only want to update/replace "OLDACCESS" with "NEWACCESS" for a subset of our users (users at Company ID 10 that have "OLDACCESS". All other users that have the "OLDACCESS" should be unchanged.

The access settings are stored in a user_settings table, and the user's account profile info such as company ID is stored in a soft_users table. Both tables are in the same database.

Luckily we have a testing database that I can practice on before making the change in our production system. I came up with the query below to do the update (from OLDACCESS to NEWACCESS) using a replace and then joining a "soft_users" table to allow me to do aa where clause to find users with company id 10 that have OLDACCEES. The issue is my script is updating all users (with any company ID) with OLDACCESS to the NEWACCESS, not just users in company 10 that have the OLDACCESS. :[

It's almost like the query is doing the update/replace but totally ignoring the join and where sections. Pretty sure I am doing something totally in line with my newbie-ness. Can someone help me out with tips to show where I am going wrong?

update user_settings
set access = replace(user_settings.access::varchar, 'OLDACCESS'::varchar, 'NEWACCESS'::varchar)
from soft_users
join user_settings us
on us.user_id = soft_users.user_id
where soft_users.company_id = '10' and us.access like 'OLDACCESS%'

Note: not sure if it matters but the database is PostgreSQL.

Thanks in advance, Mark

You are repeating the table in the FROM and UPDATE clauses.

update user_settings us
    set access = replace(us.access, 'OLDACCESS', 'NEWACCESS')
from soft_users su
where us.user_id = su.user_id and
      su.company_id = 10 and
      us.access like 'OLDACCESS%';

In addition, there should be no need to convert string constants to a string. The same is true for us.access .

Just to give you another option:

You want to update user settings, but only those where the user's company is 10. The straight-forward update statement would hence be

update user_settings
  set access = replace(access, 'OLDACCESS', 'NEWACCESS')
where access like 'OLDACCESS%'
and user_id in (select user_id from soft_users where company_id = 10);

This is how SQL is supposed to work; you try to write it like you would describe the task in English: Update user settings where certain conditions are met.

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