开发者

MYSQL SELECT optimization (simple)

开发者 https://www.devze.com 2023-03-11 07:29 出处:网络
I have a query that picks out a specific row/column from a large database. Lets say that the value returned is \'53.\'

I have a query that picks out a specific row/column from a large database. Lets say that the value returned is '53.'

I need to get:

1. The row that is 3000 rows 开发者_StackOverflowabove this value.
2. The row that is 3000 rows below this value. 

If there turn out to be only 2000 rows above the value, then I need to add the difference onto the second query.

Ex.

1. Find 3000th value up (turns out that only 2000 values are present)
2. Find 4000th value down.

Here is how I did it (this is in a stored procedure):

SET @s1 = CONCAT('INSERT INTO List1(STD)  SELECT t1.STD FROM ',t1,' AS t1 USE INDEX(STD)   WHERE   t1.STD < ',inp1,' order by STD DESC limit ', inp2);

PREPARE stmt FROM @s1;
EXECUTE stmt;


SET @lim = inp2+(inp2-(SELECT FOUND_ROWS()));
SET @s2 = CONCAT('INSERT INTO List1(STD)  SELECT t1.STD FROM ',t1,' AS t1  USE INDEX(STD)  WHERE  t1.STD >=', inp1,' order by STD ASC limit ?');

PREPARE stmt FROM @s2;
EXECUTE stmt USING @lim;

SET @minSD1 = (SELECT MIN(STD) FROM List1);
SET @maxSD1 = (SELECT MAX(STD) FROM List1);

This seems awfully round-about... is there no better way?

Also, is there really no way to use a variable table name in a stored procedure without creating ANOTHER stored procedure (with the PREPARE keyword)?


In SQL, the concept of "3000 rows above/below a given point" exists ONLY in the context of an ordered resultset, and is not defined in the database. Unless there's an algorithmic process, based on a key, to determine what is "n rows above/below" a given point, then you are stuck with actually reading the rows and counting, which is what your solution seems to attempt. I didn't verify that it actually does what you want, but either this approach or one based on cursors and counting rows is the only way to get this done.

0

精彩评论

暂无评论...
验证码 换一张
取 消