MySQL 设置数据按条件查询下的序号
一张表:mytable
有如下数据:
现在要增加一列 序号,用于表示每行记录按类型、个数降序排列时的序号。
先按照 ftype 和 fnum 排序:
select *
from mytable
order by ftype asc,fnum asc
from mytable
order by ftype asc,fnum asc
再查出当前排序下的每行的序号:
SELECT a.*,(@rownum:=@rownum+1) AS forder
FROM mytable a,(SELECT @rownum:=0) b
ORDER BY ftype ASC,fnum ASC
FROM mytable a,(SELECT @rownum:=0) b
ORDER BY ftype ASC,fnum ASC
然后修改表并将数据更新进去:
ALTER TABLE mytable ADD forder INT DEFAULT 0;
UPDATE mytable r,(
SELECT a.fid,(@rownum:=@rownum+1) AS forder
FROM mytable a,(SELECT @rownum:=0) b
ORDER BY ftype ASC,fnum ASC
) t
SET r.forder=t.forder
WHERE r.fid =t.fid
UPDATE mytable r,(
SELECT a.fid,(@rownum:=@rownum+1) AS forder
FROM mytable a,(SELECT @rownum:=0) b
ORDER BY ftype ASC,fnum ASC
) t
SET r.forder=t.forder
WHERE r.fid =t.fid
over.