简体   繁体   中英

SQL - Updating rows in table based on multiple conditions

I'm kinda newbie in SQL and I have to create a request to update multiple rows in table based on multiple conditions.

From this example:

id email                 organisationid    principaluserid role
1  john@smith.com        MULT              null            100
2  john@smith.C-100.com  C-100             1               25
3  john@doe.com          MULT              null            100
4  john@doe.C-101.com    C-101             3               50
5  john@doe.C-102.com    C-102             3               25
6  jessica@smith.com     C-102             null            25

The goal is to update all the entries from the User table where organisationid equals 'MULT' and who have only 1 principaleuserid match.

From the example above, the first 2 entries match my conditions. I need then to replace the id=2 email (john@smith.C-100.com) with the one from id=1 email (john@smith.com).

To do the job step by step, I tried to retrieve all the entries that match my condition with this request:

Edit from @The_impaler answer:

SELECT * FROM User a1 WHERE a1.organisationid = 'MULT' AND (
 SELECT COUNT(*) FROM User a2 WHERE a2.principaluserid = a1.id
) = 1;

But i'm still bugging on the way to update the entries. Any help is appreciated!

If I understand correctly, an update should do the trick:

update user u
    set u.email = um.email
    from user um
    where um.id = u.principaluserid and
          um.organizationid = 'MULT' and
          not exists (select 1
                      from user up2
                      where up2.principaluserid = u.principaluserid and
                            up2.id <> u.id
                     );

You could use an update based on join

UPDATE user u1
SET u1.email =  u2.email
FROM user u2 
WHERE u2.organisationid = 'MULT' 
       AND u1.id = u2.principaluserid 

and if you need only the value that have only a single principaluserid the you could use

UPDATE user u1
  SET u1.email =  u2.email
FROM user u2 
INNER JOIN 
(
      select principaluserid , count(*)
      from user 
      group by principaluserid 
      having count(*) =1
    ) t2 ON t2.principaluserid = u2.principaluserid 
    AND  u2.organisationid = 'MULT' 
      AND u1.id = u2.principaluserid 

Based on @The_impaler advice, I did this query that seems to answer my need:

UPDATE user u1 
  SET organisationid = (SELECT u2.organisationid FROM user u2 WHERE u1.id = u2.principaluserid),
  WHERE u1.organisationid = 'MULT' AND 
(SELECT COUNT(*) FROM user u2 WHERE u2.principaluserid = u1.id) = 1;

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