简体   繁体   中英

How can I UPDATE Table A in MySQL joining another table?

I have a stats table that has a user_id . I have a users table with an id that corresponds to the above user_id . I also have an employee flag in the users table.

I want to update all records in the stats table where the user_id is not that of an employee.

Ideally, I'd like to do this via the CodeIgniter Active Record , but I'm fine with a raw query as well.

Thanks!

EDIT My attempt

if($employee == false) {
  $this->db->where('(default_profiles.opid = 0 OR default_profiles.opid IS NULL)');  
} else {
  $this->db->where('default_profiles.opid > 0');
}
$this->db->join('weekly_stats', 'default_weekly_stats.user_id = default_profiles.user_id');

$this->db->update('default_weekly_stats', $data);

However, this just yields:

UPDATE `default_weekly_stats` SET `rank` = 1 WHERE `default_weekly_stats`.`week` = '1' AND `default_weekly_stats`.`correct_picks` = '4' AND (default_profiles.opid = 0 OR default_profiles.opid IS NULL)

Haven't tried it but maybe it should be like this:

$this->db->where_not_in('users.employee_flag', '0')->join('users', 'users.user_id = stats.user_id')->update('stats', $data);

EDIT: ( based on @dianuj answer )

$this->db->set('rank', $rank );
if($employee == false) {
  $this->db->where('(default_profiles.opid = 0 OR default_profiles.opid IS NULL)');  
} else {
  $this->db->where('default_profiles.opid > 0');
}
$this->db->update('weekly_stats ON default_weekly_stats.user_id = default_profiles.user_id');
update stats s
inner join users u on u.id = s.user_id
                   and u.employee = 0
set some_column = 'some_value'

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