简体   繁体   中英

Update table based on conditions from another table

I have 2 database tables

1- users

id  points

1  100         
2  3          
3  1 

2- user_pages

user_id  lp_flag

1        0        
2        0          
3        0    

I am trying to update lp_flag = 1 if any id points < 5 in users table.

Here is my code i want to run it using cron job only.

$Point_row = mysql_query("SELECT * FROM users WHERE points < 5 ");

 foreach($Point_row as $val){if($val['points']<5) {

mysql_query("UPDATE user_pages SET lp_flag = '1' WHERE user_id = '$id'")
}else{

mysql_query("UPDATE user_pages SET lp_flag = '0' WHERE user_id = '$id'") }
}
}

expected results

user_pages

user_id  lp_flag

1        0        
2        1          
3        1

becasue id's 2 & 3 points are <5 in users table.

You should do this in one query:

update user_pages up join
       users u
       on up.user_id = u.id
    set up.lp_flag2 = (case when u.points < 5 then 2 else 0 end);

There is no need for a loop on the application side.

You can use this:

UPDATE user_pages SET lp_flag = 1
WHERE user_id IN (SELECT id FROM users WHERE points < 5)

If default value of lp_flag is '0' than no need to use ELSE condition for UPDATE '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