[英]How to update a column of a table depending on the other column automatically in MySQL?
In my table, in one hour, 50 students will submit their marks in some exam everyday. 在我的桌子上,一小时内,每天有50名学生在某些考试中提交分数。
Following is the table 以下是表格
ID StudID Marks Rank
1 101 56
2 102 23
3 103 84
4 104 96
5 105 44
I want when all these records are inserted, the rank should get auto calculated and get insterted against each record. 我想在插入所有这些记录时,应该自动计算排名,并针对每个记录进行排名。 For example, Rank column will get filled like this:
例如,“排名”列将像这样填充:
ID StudID Marks Rank
1 101 56 3
2 102 23 5
3 103 84 2
4 104 96 1
5 105 44 4
I want to create a single query for this in mysql. 我想为此在mysql中创建一个查询。 Would it be done in a single query or will it require any functions or procedure?
将在单个查询中完成还是需要任何功能或过程? How should I write query, function or procedure for above logic in mysql?
如何在mysql中为上述逻辑编写查询,函数或过程?
Note: I have to implement above logic using PHP. 注意:我必须使用PHP实现上述逻辑。
UPDATE TableName a
INNER JOIN
(
SELECT StudID, Marks,
(SELECT COUNT(DISTINCT b.Marks)
FROM tableName b
WHERE a.Marks <= b.Marks
) as rank
FROM tableName a
ORDER BY Marks DESC
) b ON a.StudID = b.StudID
SET a.Rank = b.rank
I assuming the student rerun the insert query, so when the student submit their mark they run query insert into ... Try this: 我假设学生重新运行了插入查询,因此当学生提交自己的分数时,他们将查询插入到...中进行尝试:
INSERT INTO <thetable> (ID, StudID, Marks, Rank)
VALUES (<theid>, <thestudentid>, <themark>, NULL)
ON DUPLICATE KEY UPDATE Rank = (SELECT COUNT(*)+1
FROM <thetable>
WHERE Rank IS NOT NULL);
Another assumption: initial value for column "Rank" is NULL , or if empty string change the condition Rank IS NOT NULL
to Rank = ''
另一个假设: “ Rank”列的初始值为NULL ,或者如果为空字符串,则将条件
Rank IS NOT NULL
更改为Rank = ''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.