简体   繁体   中英

Self Join and update

I want to create a cron that do the following:

check all user referrer col where referrer_id is 0, then Join with user email and update the referrer_id with the joined user id. Here my code:

SELECT us.id usId
     , us.referrer usRe
     , us.referrer_id usReId
     , re.id reId
     , re.email 
  from users us 
  LEFT 
  JOIN users re 
    ON us.referrer = re.email 

I have to finish the update part, the problem is that the Join give me wrong results, I get in all case the user id 1.

Did you find something wrong in that query?

Tnx

If I understand correctly:

update users u join
       users r
       on u.referrer = r.email 
    set u.referrer_id = r.id
    where referrer_id is null;

I guess this answer can work for you

UPDATE users as us INNER JOIN users as re 
ON us.referrer = re.email 
SET us.referrer_id = re.id 
WHERE us.referrer_id = 0;

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