Home > Database > Mysql Tutorial > Can I Use a User-Defined Variable in a Single MySQL SELECT Statement?

Can I Use a User-Defined Variable in a Single MySQL SELECT Statement?

Barbara Streisand
Release: 2024-12-02 13:01:11
Original
924 people have browsed it

Can I Use a User-Defined Variable in a Single MySQL SELECT Statement?

Can I Define a Variable within a SELECT and Use It in the Same Statement?

The possibility of defining and utilizing a variable within the same SELECT statement is often questioned. Consider the following example:

SELECT 
    @z:=SUM(item),
    2*@z
FROM
    TableA;
Copy after login

In such a scenario, the second column consistently returns NULL. This is peculiar because a similar operation using a stored procedure functions as expected:

SELECT 
    @z:=someProcedure(item),
    2*@z
FROM
    TableA;
Copy after login

Explanation

The MySQL documentation explicitly states that assigning a value to a user variable and reading it within the same statement is unreliable. The order of evaluation for user variables is undefined and may vary based on statement elements and MySQL Server versions. Therefore, the expected results cannot be guaranteed.

Solution

To achieve the desired outcome, you can employ a subquery:

select @z, @z*2
from (SELECT @z:=sum(item)
      FROM TableA
     ) t;
Copy after login

The above is the detailed content of Can I Use a User-Defined Variable in a Single MySQL SELECT Statement?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template