1

So I found this code snippet here on SO. It essentially fakes a "row_number()" function for MySQL. It executes quite fast, which I like and need, but I am unable to tack on a where clause at the end.

select 
   @i:=@i+1 as iterator, t.* 
from 
   big_table as t, (select @i:=0) as foo

Adding in where iterator = 875 yields an error.

The snippet above executes in about .0004 seconds. I know I can wrap it within another query as a subquery, but then it becomes painfully slow.

select * from (
   select 
     @i:=@i+1 as iterator, t.* 
   from 
     big_table as t, (select @i:=0) as foo) t
where iterator = 875

The snippet above takes over 10 seconds to execute.

Anyway to speed this up?

4

2 回答 2

2

在这种情况下,您可以使用LIMITas WHERE

select 
   @i:=@i+1 as iterator, t.* 
from 
   big_table as t, (select @i:=874) as foo
LIMIT 875,1

由于您只想要记录 875,这会很快。

于 2016-08-02T04:37:19.617 回答
1

你能试试这个吗?

增加 where 子句中变量的值并对其进行检查就875可以了。

SELECT
    t.*
FROM
    big_table AS t,
    (SELECT @i := 0) AS foo
WHERE
    (@i :=@i + 1) = 875
LIMIT 1

警告:

除非您指定 order by 子句,否则不能保证每次获得所需行号时都会获得相同的行。MySQL 不确保这一点,因为表中的数据是无序集。

因此,如果您指定订单,some field则不需要用户定义的变量来获取该特定记录。

SELECT
    big_table.*
FROM big_table
ORDER BY big_table.<some_field>
LIMIT 875,1;

如果some_field被索引,您可以显着提高性能。

于 2016-08-02T04:31:24.540 回答