Question

It is possible to calculate the mnt_res column based on other columns?

CREATE ALGORITHM=UNDEFINED SQL SECURITY DEFINER
 VIEW v_test AS 
SELECT 
  func_calculate_total(...) AS mnt_total
  func_calculate_one(...) AS mnt_one,
  func_calculate_two(...) AS mnt_two,
  (mnt_total - mnt_one - mnt_two) AS mnt_res     /* Problem */
FROM ...

There is a way to do this without calling functions again? Or would you do that calculation with php for example?

Was it helpful?

Solution

Alas, this is not really possible in MySQL. You can define it, but you need to call the two functions again.

MySQL does not allow you to use subqueries in the from clause. If so, then this would be easy using a subquery. It is the only database (to my knowledge) that has this restriction.

In general, SQL does not allow you to refer to a column alias in the same select where it is defined. So that is also not possible.

One way that you can get this done is using two views:

CREATE VIEW _v_test AS 
    SELECT 
      func_calculate_total(...) AS mnt_total
      func_calculate_one(...) AS mnt_one,
      func_calculate_two(...) AS mnt_two
    FROM ...

CREATE VIEW v_test as
    SELECT vt.*, (mnt_total - mnt_one - mnt_two) AS mnt_res 
    FROM _v_test vt;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top