In the regular EMP,DEPT table configuration (stock data provided by Oracle), I have the following query to solve:
List the empno,ename,sal,job,deptno & experience of all the emps belongs to dept 10 or 20 with an exp 36 to 40 years working under the same mgr without commission
I came up with the following query:
SELECT
e.ENAME as EMPLOYEE
, m.ENAME AS MANAGER
, e.SAL, e.COMM, e.JOB, e.DEPTNO
, (SELECT @exp := ROUND(DATEDIFF(NOW(), e.HIREDATE)/(12 * 30), 1) ) AS EXP
FROM EMP e INNER JOIN EMP m ON e.MGR = m.EMPNO
WHERE e.DEPTNO in (10, 20)
AND (e.COMM IS NULL or e.COMM = 0)
AND @exp BETWEEN 35.0 AND 40.0;
Regardless of whether the query is right/wrong, when I run this query 2 times in a row, the second run (and all subsequent runs) does not produce any result (the first run does)
I looked for user defined variable questions on StackOverflow and only one of them kinda answered but still not what I was looking for. In that post, the author steampowered quotes the MySQL documentation
As a general rule, you should never assign a value to a user variable and read the value within the same statement. You might get the results you expect, but this is not guaranteed.
If that's so, then how do we prevent repeating computations in SELECT and WHERE CLAUSE?