SELECT CASE WHEN NULLID IS NULL
THEN ID
ELSE NULLID
END AS ID,
toFillTable.place
FROM
(
SELECT CASE WHEN id IS NULL
THEN @placeHolder := @placeHolder + 1
ELSE null
END as placeHolder
, r.*
FROM
(
SELECT @row := @row + 1 as row
FROM records t1, (SELECT @row := 0) t2
) s
INNER JOIN (SELECT @placeHolder := 0) t12
LEFT OUTER JOIN records r
ON s.row = r.place
order by row
) toFillTable
LEFT OUTER JOIN
(
SELECT @row1 := @row1 + 1 as nullRowPlace, t1.id as nullId
FROM records t1, (SELECT @row1 := 0) t2
where place is null
order by t1.id desc
) nullPlaceTable ON toFillTable.placeHolder = nullPlaceTable.nullRowPlace
第一个查询输出结果:
toFillTable
placeHolder Id Place
1 (null) (null)
(null) 3 2
2 (null) (null)
(null) 6 4
3 (null) (null)
4 (null) (null)
当在右行给出位置时,它会给出 ID,并在位置为空的行上给出一个名为 PlaceHolder 的计数器。
第二个查询:
nullPlaceTable
NullPlaceholder IDNull
1 5
2 4
3 2
4 1
当 place 为空时,它给出行的排名。
两者的结合给出了预期!
小提琴。
参考: