我在选择“select filed1,filed2,field3,myfunction(参数)”中调用“myfunction”作为newfield,其中条件有newfield> 0限制N“。 现在:在myfunction中我用一个表“cachetable”(用它作为缓存)填充每个结果(按记录记录)但最后在“cachetable”中,行数不符合主要选择的LIMIT子句返回找到的所有记录(如果没有表达LIMIT)。 任何帮助非常感谢! 非常感谢。 d
答案 0 :(得分:1)
我用MySQL 5.5.38对此进行了测试,但我无法重现您描述的问题。如果您想进一步排查问题,则必须编辑问题并提供有关查询的详细信息以及您如何调用myfunction()。
以下是设置:
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 ;
这是演示。我测试了是否使用ORDER BY
,我测试了将LIMITed查询放在子查询中,以确保在调用myfunctions()之前只有两行返回到外部查询。您可以看到,无论我如何调用它,只有两行插入到缓存中。
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 |
+------+