@@ -7,13 +7,13 @@ def as_sql(self, with_limits=True, with_col_aliases=False):
7
7
with_limit_offset = with_limits and (
8
8
self .query .high_mark is not None or self .query .low_mark
9
9
)
10
- print ('LIMIT - ' + str (self .query .low_mark ) + ':' + str (self .query .high_mark ))
11
10
if self .query .select_for_update or not with_limit_offset :
12
11
return super ().as_sql (with_limits , with_col_aliases )
13
12
try :
14
13
extra_select , order_by , group_by = self .pre_sql_setup ()
15
14
16
- limit , offset = self .connection .ops ._get_limit_offset_params (self .query .low_mark , self .query .high_mark )
15
+ offset = self .query .low_mark + 1 if self .query .low_mark else 0
16
+ limit = self .query .high_mark
17
17
18
18
distinct_fields , distinct_params = self .get_distinct ()
19
19
# This must come after 'select', 'ordering', and 'distinct'
@@ -45,9 +45,11 @@ def as_sql(self, with_limits=True, with_col_aliases=False):
45
45
result += distinct_result
46
46
params += distinct_params
47
47
48
+ first_col = ""
48
49
out_cols = []
49
50
col_idx = 1
50
51
for _ , (s_sql , s_params ), alias in self .select + extra_select :
52
+ first_col = s_sql if not first_col else first_col
51
53
if alias :
52
54
s_sql = "%s AS %s" % (
53
55
s_sql ,
@@ -63,14 +65,18 @@ def as_sql(self, with_limits=True, with_col_aliases=False):
63
65
out_cols .append (s_sql )
64
66
65
67
order_by_result = ""
68
+
66
69
if order_by :
67
70
ordering = []
68
71
for _ , (o_sql , o_params , _ ) in order_by :
69
72
ordering .append (o_sql )
70
73
params .extend (o_params )
71
74
order_by_result = "ORDER BY %s" % ", " .join (ordering )
72
- if offset :
73
- out_cols .append ("ROW_NUMBER() OVER (%s) AS row_number" % order_by_result )
75
+ elif offset :
76
+ order_by_result = "ORDER BY %s" % first_col
77
+
78
+ if offset :
79
+ out_cols .append ("ROW_NUMBER() %s AS row_number" % ("OVER (%s)" % order_by_result if order_by_result else "" ))
74
80
75
81
result += [", " .join (out_cols ), "FROM" , * from_ ]
76
82
params .extend (f_params )
@@ -147,8 +153,8 @@ def as_sql(self, with_limits=True, with_col_aliases=False):
147
153
if offset :
148
154
query = "SELECT * FROM (%s) WHERE row_number between %d AND %d ORDER BY row_number" % (
149
155
query ,
150
- limit ,
151
156
offset ,
157
+ limit ,
152
158
)
153
159
return query , tuple (params )
154
160
except :
0 commit comments