您可以使用临时表来存储值并UPDATE
通过连接从中获取值。
/* Store query result in a temporary table */
CREATE TEMPORARY TABLE ranks AS
SELECT @rownum:=@rownum+1 number, member_id FROM members, (SELECT @rownum:=0) r ORDER BY col1 DESC, col2 DESC;
/* And join against it to update your members.number column */
UPDATE
members
JOIN ranks ON members.member_id = ranks.member_id
SET members.number = ranks.number;
DROP TABLE ranks;
实际上,通过我刚才的测试,我能够在没有临时表的情况下做到这一点。我不认为 MySQL 会允许从子查询更新同一个表,但显然它允许与相关子查询一起使用。
UPDATE
members
/* JOIN against a subquery which returns the rank values */
JOIN (
SELECT @rownum:=@rownum+1 number, member_id
FROM members, (SELECT @rownum:=0) r
ORDER BY col1 DESC, col2 DESC
) ranks ON members.member_id = ranks.member_id
/* And set the number column to the rank */
SET members.number = ranks.number;
SQLfiddle.com 演示