http://sqlfiddle.com/#!2/1840d/1
我有一个id和地方表,是否可以在指定的地方设置行?
获得
ID PLACE
5 (null)
3 2
4 (null)
6 4
2 (null)
1 (null)
而不是
ID PLACE
6 4
5 (null)
4 (null)
3 2
2 (null)
1 (null)
对于这个数据,它意味着将一个place = 2的行作为结果中的第二行,将row = 4作为结果中的第四行,而其他行则按原始顺序覆盖它们。
回答
select * from records
order by FIELD(ID, 5,3,4,6,2,1)
既好又有趣,但错了。
答案 0 :(得分:2)
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为null时,它给出行的等级。
两者的结合给出了预期的结果!
参考: