我需要在MSSQL server 2008中将LIMIT
和OFFSET
应用于原始查询(不进行修改)。
假设原始查询是:
SELECT * FROM energy_usage
(但它可以是任意的SELECT查询)
这就是我到目前为止所提出的:
1。它可以满足我的需求,但查询会生成额外列 row_number ,这是我不需要的。
WITH OrderedTable AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS row_number, * FROM energy_usage
)
SELECT * FROM OrderedTable WHERE row_number BETWEEN 1 AND 10
2。这个因某些原因无效并返回以下错误。
SELECT real_sql.* FROM (
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS row_number, * FROM (SELECT * FROM energy_usage) as real_sql) as subquery
WHERE row_number BETWEEN 1 AND 10
更常见的情况是:
SELECT real_sql.* FROM (
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS row_number, * FROM (real sql query) as real_sql) as subquery
WHERE row_number BETWEEN {offset} + 1 AND {limit} + {offset}
错误:
列前缀'real_sql'与表名或别名不匹配 查询中使用的名称。
答案 0 :(得分:1)
只是不要把它放在SELECT
列表中:
WITH OrderedTable AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS row_number, *
FROM energy_usage
)
SELECT col1, col2, col3 FROM OrderedTable WHERE row_number BETWEEN 1 AND 10;
SELECT *
是常见的反模式,无论如何都应该避免。加ORDER BY (SELECT 1)
将无法保证执行之间的稳定排序。
如果您只需要十行,请使用:
SELECT TOP 10 *
FROM energy_usage
ORDER BY ...
不幸的是,你不会得到Selecting all Columns Except One
这样的好东西WITH OrderedTable AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS row_number, *
FROM energy_usage
)
SELECT * EXCEPT row_number FROM OrderedTable WHERE row_number BETWEEN 1 AND 10;
答案 1 :(得分:0)
这可以解决问题。
"columns": [
{data: "id", name: "aaa", sortable: false},
{data: "userid", name: "userid", sortable: false},
{data: "group_id", name: "group_id", sortable: false},
{data: "group_name", name: "group_name", sortable: false},
{data: "group_member", name: "group_member"},
{data: "group_fee", name: "group_fee"},
{data: "dynamic_type", name: "dynamic_type"},
{data: "dynamic_id", name: "dynamic_id"},
{data: "content", name: "content", sortable: false},
{data: "images", name: "images", sortable: false},
{data: "money", name: "money"},
{data: "is_audit", name: "is_audit", sortable: false},
{data: "audited_at", name: "audited_at", sortable: false}