在mysql中使用group by将一个字段值重用到其他字段

时间:2013-01-15 10:52:48

标签: mysql function stored-procedures

我在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;

有可能吗?

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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 |
+--------------------------+-------------+