0

我在mysql中有以下查询:

INSERT INTO table_name(field1, field2, field3, field4......)
SELECT  field1, field2, 
        function_name(field3,'2012-01-01'), 
        function_name(field3,'2012-01-01')/field1..... 
from table_name2 group by field1, field2;

我的问题是上述查询工作正常,但由于我多次使用 function_name(field3,'2012-01-01') ,因此执行时间过长。现在我希望我将执行一次 function_name(field3,'2012-01-01') 并将用于 field3 和 field4。我不会再次为 field4 调用 function_name,因为我已经为 field filed3 执行了它。

所以查询应该是这样的

INSERT INTO table_name(field1, field2, field3,field4......)
SELECT  field1, field2, 
         @res:=function_name(field3,'2012-01-01'), 
        @res/field1..... 
 from table_name2 
 group by field1, field2;

可能吗?

4

2 回答 2

1

您可以使用

INSERT INTO table_name(field1, field2, field3, field4......) SELECT field1, field2, function_name(field3,'2012-01-01') as @res, @res/field1..... from table_name2 group by field1, field2;

于 2013-01-15T10:58:13.540 回答
1

请将查询更改为

"INSERT INTO table_name(field1, field2, field3, field4......) SELECT field1, field2, @res := function_name(field3,'2012-01-01'), @res/field1..... from table_name2 group by field1, field2;

这与您指定的相同。这是正确的我已经这样检查了

mysql> select ( @point := sum(points)), @point/12  from votes;
+--------------------------+-------------+
| ( @point := sum(points)) | @point/12   |
+--------------------------+-------------+
|                       20 | 1.000000000 |
+--------------------------+-------------+
于 2013-01-16T04:34:03.203 回答