Daniel Jensen
Daniel Jensen

Reputation: 141

Update one table if value is equal in other table

I may have tried to reach too high this time, but I hope this can be done. I have a table called liga like this:

uid  |  name  |  games  |  points  |
___________________________________
1    | Daniel |    0    |    0     |
2    | Mikkel |    0    |    0     |

Where uid is short for user id. Then I have a table called kamp2 like this:

uid  |  k1    |  k1r    |  k2   |  k2r   |  week  |
__________________________________________________
1    |  1     |  2-1    |  X    |  2-2   |  14    |
2    |  2     |  1-1    |  1    |  2-1   |  14    |

These data is submitted by the user (attached to the uid).
Now, what I would like is a form, where I write the results of a soccermatch, something like:

<input type="text" name="k1">... and so on...

... and then I should write the correct results. So, to my actual question:
Let's say the first match (k1=the winner(1X2) and k1r=result) was 2-1, I would like the form to update the liga-table with something like:

If (k1 == 1 AND k1r == 2-1) UPDATE liga SET point = point + 5 WHERE uid = $uid;
else if 
(k1r == 2-1 AND k1 != 1) UPDATE liga SET point = point + 3 WHERE uid = $uid ;
else if 
(k1 == 1 AND k1r != 2-1) UPDATE liga SET point = point + 1 WHERE uid = $uid ;

But how is this possible? Should I SELECT the kamp2 table first and then use it or maybe JOIN the two tables or how? If this question is too "big" to answer, just let me know :) I don't want you to give me the exact code, just to guide me :) Hope it's okay!

Upvotes: 0

Views: 55

Answers (3)

Zunair Fatimi
Zunair Fatimi

Reputation: 116

You can either use the concept of triggers to achieve this task:

https://www.sitepoint.com/how-to-create-mysql-triggers/

You'll have to create an after Update/insert trigger on kamp2 table and in that trigger you'll update liga table

Or else handle this by backend php script.

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269633

You can join the tables together and then do the update with CASE logic:

UPDATE liga l JOIN
       kamp2 k
       ON l.uid = k.uid
    SET point = (CASE WHEN k.k1 = '1' and k.k1r = '2-1' THEN point + 5
                      WHEN k.k1r = '2-1' AND k.k1 <> '1' THEN point + 3 
                      WHEN k.k1 = '1' AND k.k1r <> '2-1' THEN point + 1 
                      ELSE point
                 END)
    WHERE l.uid = $uid ;

Upvotes: 2

Sunny Kumar
Sunny Kumar

Reputation: 836

you can't update the same record with condition of that as well.

You need to use sub query to update that.

UPDATE data_table t, (SELECT DISTINCT ID, NAME, VALUE FROM data_table WHERE VALUE IS NOT NULL AND VALUE != '') t1 SET t.VALUE = t1.VALUE WHERE t.ID = t1.ID AND t.NAME = t1.NAME

Upvotes: 0

Related Questions