How to use temp field in arithmetic operation in MySQL


I want to do some arithmetic in query using temporary field.

SELECT point, '5' AS bonus, (bonus*2) AS total FROM arithmetic

but the temp field is unknown

Unknown column 'bonus' in 'field list'

how can i use or called temp field in query?

>Solution :

You can either use a user variable here to store the valus of bonus, or use a subquery/CTE. Assuming the latter, and that you are running MySQL 8+, we can try:

WITH cte AS (
    SELECT point, 5 AS bonus
    FROM arithmetic

SELECT point, bonus, 2*bonus AS total
FROM cte;

Leave a ReplyCancel reply