I have "myfunction" called inside a select "select filed1, filed2, field3, myfunction(parameter) as newfield where conditions having newfield > 0 limit N". Now: inside myfunction I populate a table "cachetable" (using it as a cache) with every single result (record by record) but at the end in "cachetable" the number of rows doesn't respect the LIMIT clause of the main select returning all the records found (if LIMIT wouldn't have been expressed). any help is very appreciated! thanks a lot. d
1 Answer
I tested this with MySQL 5.5.38, but I could not reproduce the problem you described. If you want further troubleshooting, you'll have to edit your question and give more detail about your query and how you're calling myfunction().
Here's the setup:
USE test;
CREATE TABLE cachetable (
id INT
);
CREATE TABLE mytable (
id INT PRIMARY KEY,
newfield INT
);
INSERT INTO mytable (id, newfield) VALUES
(1, 42), (2, 7), (3, 5), (4, 0), (5, 42), (6, 0);
DELIMITER //
CREATE FUNCTION myfunction (param INT) RETURNS INT
DETERMINISTIC MODIFIES SQL DATA
BEGIN
INSERT INTO cachetable (id) VALUES (param);
RETURN 0;
END//
DELIMITER ;
Here's the demo. I tested with and without ORDER BY, and I tested putting the LIMITed query inside a subquery, to ensure that only two rows are returned to the outer query before calling myfunctions(). You can see that no matter how I call it, only two rows are inserted into cachetable.
SELECT *, myfunction(id) FROM mytable WHERE newfield > 0 LIMIT 2;
+----+----------+----------------+
| id | newfield | myfunction(id) |
+----+----------+----------------+
| 1 | 42 | 0 |
| 2 | 7 | 0 |
+----+----------+----------------+
SELECT * FROM cachetable;
+------+
| id |
+------+
| 1 |
| 2 |
+------+
TRUNCATE cachetable;
SELECT *, myfunction(id) FROM mytable WHERE newfield > 0 ORDER BY newfield LIMIT 2;
+----+----------+----------------+
| id | newfield | myfunction(id) |
+----+----------+----------------+
| 3 | 5 | 0 |
| 2 | 7 | 0 |
+----+----------+----------------+
SELECT * FROM cachetable;
+------+
| id |
+------+
| 3 |
| 2 |
+------+
TRUNCATE cachetable;
SELECT *, myfunction(id) FROM (SELECT * FROM mytable WHERE newfield > 0 ORDER BY newfield LIMIT 2) AS t;
+----+----------+----------------+
| id | newfield | myfunction(id) |
+----+----------+----------------+
| 3 | 5 | 0 |
| 2 | 7 | 0 |
+----+----------+----------------+
SELECT * FROM cachetable;
+------+
| id |
+------+
| 3 |
| 2 |
+------+
ORDER BY.