0

I'm constructing a select statement that will later be the value of an insert statement. Most of the columns will be calculated fields. I recently learned that you can reuse calculated fields during select:

select
  id,
  @sum1 := col1 + col2 as colSum1,
  @total1 := @sum1 + col3 as colTotal1,
  @gtotal := @sum1 + total1 as colGTotal

the result set will be 4 columns: id, colSum1, colTotal1, and colGTotal. I need the resulting column to be just the last column colGTotal.

Again this select statement will be a value of an insert.

INSERT INTO tbltest VALUES (SELECT...)

I just need to insert the colGTotal

So I guess what I need is variable declaration and assignment inside the select statement (can't be outside) but EXCLUDE it as one of the resulting columns to be fed on the insert statement.

4

1 回答 1

0

如果可以,请重写查询以生成单列:

select col1 + col2 + col1 + col2 + col3 as colGTotal

或者,您可以将此 SELECT 语句用作子查询,并选择您想要的列:

INSERT INTO tbltest VALUES (SELECT colGTotal FROM (SELECT id, @sum1 ...) AS foo)
于 2012-06-21T15:26:14.510 回答