Home > Database > Mysql Tutorial > Why Can't I Use Column Aliases Directly in the Same SELECT Statement's Calculations?

Why Can't I Use Column Aliases Directly in the Same SELECT Statement's Calculations?

DDD
Release: 2025-01-14 09:28:43
Original
504 people have browsed it

Why Can't I Use Column Aliases Directly in the Same SELECT Statement's Calculations?

Restrictions on directly using column aliases for calculations in SQL queries

In the given SQL query, trying to use the column aliases ROUND(avg_time * cnt, 2) and avg_time in the expression cnt results in the error "Column 'avg_time' does not exist".

The root cause lies in the order of evaluation of the SELECT statements. The program processes the entire SELECT statement simultaneously, so the alias value cannot be recognized at that point in time.

Solution: Use nested subqueries

To solve this problem, the query can be encapsulated using a subquery, effectively creating an intermediate data set. In this subquery, you can create the required column aliases avg_time and cnt.

<code class="language-sql">SELECT stddev_time, max_time, avg_time, min_time, cnt, ROUND(avg_time * cnt, 2) as slowdown
FROM (
    SELECT 
        COALESCE(ROUND(stddev_samp(time), 2), 0) as stddev_time, 
        MAX(time) as max_time, 
        ROUND(AVG(time), 2) as avg_time, 
        MIN(time) as min_time, 
        COUNT(path) as cnt, 
        path
    FROM 
        loadtime
    GROUP BY
        path
    ORDER BY
        avg_time DESC
    LIMIT 10
) X;</code>
Copy after login

Now, when executing this query, the subquery is evaluated first, producing a dataset containing the required column aliases. Subsequent SELECT statements can then successfully reference these aliases.

The above is the detailed content of Why Can't I Use Column Aliases Directly in the Same SELECT Statement's Calculations?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template