I'm new on mysql and I don't know the terms, so I'll speak as I can. Here my problem:
I have works
table, it have columns: id
, date
, and done
.
+----+---------------------+------+
| id | date | done |
+----+---------------------+------+
| 1 | 2020-05-01 14:22:34 | 10 |
| 2 | 2020-05-02 14:22:45 | 50 |
| 3 | 2020-05-03 14:23:00 | 30 |
| 4 | 2020-05-04 14:23:13 | 100 |
| 5 | 2020-05-05 14:23:24 | 25 |
+----+---------------------+------+
I want to select all of them with +1 new column, named cummulative_done
. I use this sql command to get the result I want.
SET @cdone := 0;
SELECT *, (@cdone := @cdone + done) as cummulative_done
FROM works;
Result:
+----+---------------------+------+------------------+
| id | date | done | cummulative_done |
+----+---------------------+------+------------------+
| 1 | 2020-05-01 14:22:34 | 10 | 10 |
| 2 | 2020-05-02 14:22:45 | 50 | 60 |
| 3 | 2020-05-03 14:23:00 | 30 | 90 |
| 4 | 2020-05-04 14:23:13 | 100 | 190 |
| 5 | 2020-05-05 14:23:24 | 25 | 215 |
+----+---------------------+------+------------------+
Then, I want that result to be filtered by cummulative_done
using sql WHERE
. On my first try, I use this sql command.
SET @cdone := 0;
SELECT *, (@cdone := @cdone + done) as cummulative_done
FROM works
WHERE cummulative_done <= 100;
And it give me error: Error in query (1054): Unknown column 'cummulative_done' in 'where clause'
.
After that, I searched on google and got a solution using this sql command.
SET @cdone := 0;
SELECT *, (@cdone := @cdone + done) as cummulative_done
FROM works
WHERE @cdone + done <= 100;
It result:
+----+---------------------+------+------------------+
| id | date | done | cummulative_done |
+----+---------------------+------+------------------+
| 1 | 2020-05-01 14:22:34 | 10 | 10 |
| 2 | 2020-05-02 14:22:45 | 50 | 60 |
| 3 | 2020-05-03 14:23:00 | 30 | 90 |
+----+---------------------+------+------------------+
It give me the result I want, but I don't understand why it works and why mine not works.
From that, I realized my understanding of sql SELECT
and WHERE
is wrong. Can anyone explain to me how sql SELECT
and WHERE
works generally? After that please explain why my first try not works and why the solution works.
If can, I prefer step-by-step
or deep
explaination but still easy to understand
. Thanks.