列出MySQL中乱序的记录

时间:2018-11-19 19:09:59

标签: mysql sql sequence

我有一个MySQL简单表

apostrophe-pieces-pages

第3和第6条记录在日期上不按顺序。我想查询从表中返回REFNUM的3和6。基于类似的问题,我构造了查询:

+--------+------------+
| REFNUM | TSTAMP     |
+--------+------------+
| 1      | 2018-JUN-1 |
| 2      | 2018-JUN-3 |
| 3      | 2018-JAN-1 |
| 4      | 2018-JUN-4 |
| 5      | 2018-JUN-6 |
| 6      | 2018-JAN-2 |
+--------+------------+

但是我总是得到空结果。有人可以解释为什么以及如何纠正吗?

3 个答案:

答案 0 :(得分:0)

您正在按refnum进行分区,这似乎是唯一的。这意味着两个值始终都是1

SELECT q.*
FROM (SELECT q.*,
             ROW_NUMBER() OVER (ORDER BY REFNUM ) AS sequenceCorrect,
             ROW_NUMBER() OVER (ORDER BY TSTAMP) AS sequenceActual
      FROM queries q
     ) q
WHERE sequenceCorrect <> sequenceActual
ORDER BY REFNUM;

您还可以使用单个窗口功能执行此操作:

SELECT q.*
FROM (SELECT q.*,
             MAX(TSTAMP) OVER (ORDER BY REFNUM) as MAX_TSTAMP
      FROM queries q
     ) q
WHERE MAX_TSTAMP <> TSTAMP
ORDER BY REFNUM;

编辑:

如果您特别想要颠倒顺序的商品,请使用lag()

SELECT q.*
FROM (SELECT q.*,
             LAG(TSTAMP) OVER (ORDER BY REFNUM) as PREV_TSTAMP
      FROM queries q
     ) q
WHERE PREV_TSTAMP > TSTAMP
ORDER BY REFNUM;

答案 1 :(得分:0)

关于带有子查询的简单查询(假设TSTAMPDATE列):

SELECT REFNUM
FROM queries AS outer_query
WHERE TSTAMP < (SELECT TSTAMP FROM queries WHERE REFNUM = outer_query.REFNUM-1);

尝试HERE。希望对您有所帮助。

答案 2 :(得分:0)

通过检查当前的TSTAMP是否小于先前ID的TSTAMP,假设ID之间可能存在间隙:

SELECT *  FROM queries q WHERE 
    (q.TSTAMP < 
    (SELECT qq.TSTAMP FROM queries qq WHERE REFNUM = 
    (SELECT MAX(REFNUM) FROM queries WHERE REFNUM < q.REFNUM)))