[英]Adding values into a new mySQL db table column depending on an old column
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.
我是PHP和DB的新手,所以我真的不知道如何从这开始。 So I want to want to make a sorting inside a DB where the IDs differ too much.
所以我想要在ID过多的DB中进行排序。 (that means that the first ID starts with 34 and the next one is something like 43 next is 55 etc.)
(这意味着第一个ID以34开头,下一个ID是43,接下来是55等)
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. 现在我想要做的是根据PID中的值更改VALUE列中的值。
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. 这意味着如果在PID中值等于1,则同一行上的VALUE应变为1001,下一个值为1002,下一个1003.如果PID = 2,则VALUE应更改为2001然后2002年然后2003等。这将是一个已经存在的表,但我还希望每次在该表中添加新语句时都包含VALUE值。 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 如果PID等于1,则检查VALUE列以获得以“1”开头的最高编号,使其为+1并将其添加到该行的列中
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. 干杯,K。
You can use UPDATE .. JOIN
and join to a derived table containing the "rank" of each ID
, and update accordingly : 您可以使用
UPDATE .. JOIN
并加入包含每个ID
的“rank”的派生表,并相应地更新:
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. 它通过条件
s.pid = s2.pid AND s.id >= s2.id
连接到它自己,在单词中 - 包含我在我之前发生的相同PID
,所以第一个将加入到1个记录,第二个到两个等等..然后你只需将value
列更新为pid*1000
,加上等级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.