What will be the SQL query for this UPDATE operation? -
i using mysql 5.1. have database tables users , users_group_mapping.
user table : userid, username, points 1 user1 10 2 user2 21 3 user3 7 4 user4 44 users_group_mapping table : userid, usergroupid 1 1 2 2 4 2 4 1 4 3
and in allocation process have allocate points corresponding groups users. test data :
data : $dtarr = array( [1] => 40, [2] => 80, [3] => 100 )
in array $dtarr, key attribute 'usergroupdid' in users_group_mapping table , value attribute points updated in users table.
e.g. if usergroupid = 2 , points given = 40 users_group_mapping table users in usergroup '2' - userids '2' & '4' - both users 40 points each. userid '4' 40 points allocated through usergroup '2' though user belongs usergoups '1' & '3' also.
what sql update query operation?
please guide me..!! in advance.!!
if have in database , if want in order given table users_group_mapping, should add sequence column table , create new table data
. have this:
user table : userid, username, points 1 user1 10 2 user2 21 3 user3 7 4 user4 44 users_group_mapping table : userid, usergroupid rowseq 1 1 1 2 2 2 4 2 3 4 1 4 4 3 5 data table : usergroupid, points 1 40 2 80 3 100
than sql require follows:
update user join users_group_mapping using (userid) join data on data.usergroupid=users_group_mapping.usergroupid left join users_group_mapping x on x.userid=user.userid , x.rowseq < users_group_mapping.rowseq set user.points = user.points + data.points x.userid null
if not want add points existing points, set them, of course use
update user join users_group_mapping using (userid) join data on data.usergroupid=users_group_mapping.usergroupid left join users_group_mapping x on x.userid=user.userid , x.rowseq < users_group_mapping.rowseq set user.points = data.points x.userid null
edit
here solution if can not change data structure (php+mysql)
$userids[] = array(); $result = mysql_query("select * user"); while ($row = mysql_fetch_assoc($result)) { $userids[] = $user_row['userid']; }; foreach($userids $userid) { $result = mysql_query("select usergroupid users_group_mapping userid = $userid"); $row = mysql_fetch_assoc($result)); # need first matching row no cycle $usergroupid = intval($row['usergroupid']); $points = $dtarr[$usergroupid]; mysql_query("update user set points = points + $points user.userid = $userid"); };
please not although code correct, because not hard solve this, there stupid mistakes (syntax errors etc) not have time debug it. should give answer.
Comments
Post a Comment