如何根据一个MySQL查询中的另外两列为每行设置一个数字?

时间:2013-01-12 22:58:39

标签: mysql

假设我有一个名为 members 的表,具有以下结构:

member_id, col1, col2, number

现在,如果我运行此查询:

SELECT @rownum:=@rownum+1 number, member_id 
FROM members, (SELECT @rownum:=0) r ORDER BY col1 DESC, col2 DESC

我为每一行得到一个数字。是否可以将此编号分配给每行的编号列?

例如,如果表包含此数据:

1 1000 1.2 0
2 8700 1.1 0
3 1000 1.1 0

第一行数字列应设置为2,第二行设置为1,第三行设置为3.

2 个答案:

答案 0 :(得分:2)

您可以使用临时表来存储值,并使用连接来存储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 demo

答案 1 :(得分:0)

你可以试试这个

update members A
INNER JOIN
(
    SELECT @rownum:=@rownum+1 number, member_id 
    FROM members, (SELECT @rownum:=0) r 
    ORDER BY col1 DESC, col2 DESC
) B ON A.member_id = B.member_id
SET A.number = B.number;