Reputation: 31
ID | PID | NAME | VALUE |
-------------------------------------
60 | 1 | Test1 | 9999 |
21 | 2 | Test2 | 9999 |
44 | 1 | Test3 | 9999 |
37 | 4 | Test4 | 9999 |
24 | 1 | Test5 | 9999 |
Hey all! I am kind of new to PHP and DBs so I really dont know how to start with this. So I want to want to make a sorting inside a DB where the IDs differ too much. (that means that the first ID starts with 34 and the next one is something like 43 next is 55 etc.)
I have a table which looks like the one above.
Now what I would like to do is changing the values in the column VALUE depending on the values which are in PID.
This means that if in PID the value equals 1 the VALUE on the same row should become 1001 and for the next one 1002, next 1003. If PID = 2 then VALUE should be changed to 2001 then 2002 then 2003 etc. This would be for an already existing table but I would also like to include the VALUE values everytime I add a new statement into that table. So a simple check in pseudocode:
If PID equals 1 then check VALUE column for the highest number that starts with "1" make it +1 and add it into the column of that row
Is that possible to do? what would you guys suggest me to do instead (to make things easier)? If you need further info, tell me please and I will try to explain things better, I dont know if my explanation says what I'm trying to do.
Thank you in advance.
Cheers, K.
Upvotes: 1
Views: 143
Reputation: 40481
You can use UPDATE .. JOIN
and join to a derived table containing the "rank" of each ID
, and update accordingly :
UPDATE YourTable t
JOIN(SELECT s.ID,s.PID,COUNT(*) as cnt
FROM YourTable s
JOIN YourTable s2
ON(s.pid = s2.pid AND s.id >= s2.id)) p
ON(t.id = p.id)
SET t.value = (1000*t.pid) + p.cnt
The inner query here basically "ranks" the data by a self join. It joins to it self by the condition s.pid = s2.pid AND s.id >= s2.id
, in words - Same PID
that happen before me including me, so the first one will join to 1 record, the second to two and so on.. Then you just update value
column to pid*1000
, plus the rank.
Upvotes: 1