sql - Using ROW_NUMBER() OVER() in subquery
问题描述
I'm encountering a problem, actually I'm using a query like this:
SELECT *
FROM
(SELECT
ROW_NUMBER() OVER() as VAL_RRN,
T1.FIELD1 AS FIELD1,
T1.FIELD2 AS FIELD2
FROM
MYTABLE1 AS T1) AS subquery
WHERE
VAL_RRN >= X
FETCH FIRST 10 ROWS ONLY
This query is used to display 10 results at one time to the user, and the X
variable is used with a scroll system to let the user navigate through the results.
This query works well (but I don't know if this is the best way to do it).
Anyway, what I actually need to do is a little different:
SELECT *
FROM
(SELECT
ROW_NUMBER() OVER() as VAL_RRN,
T1.FIELD1 AS FIELD1,
T1.FIELD2 AS FIELD2,
COALESCE((SELECT '1'
FROM MYTABLE1 AS T2
WHERE T1.FIELD1 = T2.FIELD2 FETCH FIRST ROW ONLY), '0') AS FIELD3 FROM MYTABLE1 AS T1) AS subquery
WHERE
VAL_RRN >= X
FETCH FIRST 10 ROWS ONLY
The COALESCE
clause is used to know if one row has others rows referencing it.
In MYTABLE1
the FIELD1
is the primary key and the FIELD2
is a Foreign Key defined with:
CONSTRAINT CONSTRAINT_NAME FOREIGN KEY
(FIELD2) REFERENCES MYTABLE (FIELD1) ON DELETE SET NULL
the MYTABLE
table can have row which references other rows.
But when I'm using the second type of query, the actual value of row_number() over()
is completely random, and I don't know why. I have tried to use VALUE()
instead of COALESCE()
but this doesn't seem to work, any ideas?
解决方案
You should use row_number() over(order by ...)
.
Row enumeration is unpredictable otherwise.
推荐阅读
- c# - Unity3D 中的 SabreCSG 无法构建(错误 CS0246:找不到类型或命名空间名称“***”)
- javascript - 为什么 {{ list.title }} 没有显示
- php - 在 1 个表中显示 2 个数组
- visual-studio-code - 内置问题匹配器在哪里定义?
- r - 从R中的数据中删除上五分位数和下五分位数
- java - 将外部 jgroups 模块添加到 Wildfly (native-s3-ping)
- ios - 快速防止UITab栏图标和文本上的渐变?
- node.js - 在 Windows 中查看 Nodejs 环境变量
- c++ - 排序和输出到文件时出现问题
- python - singledispatchmethod 使用它使用的类?