简体   繁体   中英

Adding values in column based on another column of separate table sql

I have two tables

Followers_list

User_name    Followers_name
user 1          user 2
user 1          user 3
user 3          user 4

Final_table

 User_name         M_User     Total    Follower
  user 1           user2       8         NULL
  user 2           user 3      9         NULL
  user 3           user 4      2         NULL

What I want is alter table like this

 User_name         M_User     Total    Follower
  user 1           user2       8         1
  user 2           user 3      9         0
  user 3           user 4      2         1

Basically I want to match the two tables and see if the user_name is following m_user and put 1 if yes else 0 this is what I have done so far but it's giving me "FL"."F_USER_NAME": invalid identifier error.

UPDATE FINAL_TABLE   SET FB.FOLLOWER =  (CASE
        WHEN FB.USER_NAME = FL.USER_NAME AND FB.M_USER = FL.F_USER_NAME 
     THEN       1
        ELSE  0
    END);

    FROM
        FINAL_TABLE fb,
        FOLLOWERS_LIST fl

How can I solve this problem?

You can use a subquery to retrieve the value you want to assign, like this :

UPDATE Final_table FB
  SET FB.FOLLOWER =
    (SELECT CASE WHEN COUNT(*) > 0 THEN 1
                       ELSE  0 END
        FROM FOLLOWERS_LIST fl
        WHERE FB.USER_NAME = FL.USER_NAME AND FB.M_USER = FL.F_USER_NAME);

Here is my testing : https://livesql.oracle.com/apex/livesql/s/el9abzc95lirn6mrt4l0lfod7

If follower_list table has unique value combination, you don't even need the CASE clause:

UPDATE final_table a SET a.follower = (SELECT COUNT(*) FROM follower_list b WHERE a.user_name = b.user_name AND b.followes_name = a.m_user);

That's because the COUNT(*) aggregate function returns always a value even if there are no records in the target table and if there is just one entry for that combination of user_name and followers_name. That way you will always get 0 or 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