mysql - 以绝对位置排序结果

标签 mysql

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 的行作为结果中的第二行,将 place = 4 的行作为结果中的第四行,而其他行按其原始顺序覆盖它们。

回答

select * from records 
order by FIELD(ID, 5,3,4,6,2,1)

很好又有趣,但是错了。

最佳答案

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)

当右行给出place时,它给出Id,并在place为空的行上给出一个名为PlaceHolder的计数器。

第二个查询:

nullPlaceTable 

NullPlaceholder    IDNull
     1                5
     2                4
     3                2
     4                1

当 place 为空时,它给出行的排名。

两者的结合达到了预期!

Fiddle.

引用:

关于mysql - 以绝对位置排序结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16076880/

相关文章:

php - 在单元格内列出并以与 php 相同的方式输出

mysql replication incompatible statements问题

mysql - SQLSTATE[42S22] : Column not found: 1054 Unknown column 'adjusted_amount' in 'field list'

php - SQL查询中的printf或类似内容?

sql - 如何在查询中合并两个表

mysql - mysql存储过程中不存在临时表

mysql - 在所有 MySql 表上要求 SSL

c# - 实体模型 .net 从 MySQL 性能问题中查询 100 万条记录

php - 如何为此添加标题、描述和关键字表单?

python - pandas read_sql 异常慢