My Goal:
Select middle row(s) of a table.
What have I tried?
I followed the approach mentioned in https://stackoverflow.com/a/33168093/282155.
Here's my code:
SELECT @a:=FLOOR((COUNT(*)-1)/2) FROM <Table> ORDER BY <Column>;
PREPARE STMT FROM 'SELECT * FROM <Table> LIMIT ?, 1';
EXECUTE STMT USING @a;
But my execute statement throws error:
ERROR 1210 (HY000) at line <line no>: Incorrect arguments to EXECUTE
My observations:
- Floor of integer works fine when used in the prepared statement. e.g.
FLOOR(COUNT(*)-1)
- Execution of floor of decimal also works fine when used in Select statement:
SELECT FLOOR((COUNT(*)-1)/2) FROM <Table>;
I am confused why my code is not working.
Thanks in advance.
CodePudding user response:
Consider using the following equivalent (yet valid) option.
SELECT @sql := CONCAT('SELECT *
FROM <Table>
ORDER BY <Column>
LIMIT ', FLOOR((COUNT(*)-1)/2), ', 1') FROM <Table>;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
And don't forget to deallocate your statement preparation.
Check the demo here.