I am trying to understand SQL Self-joins. I have the following table Weather
+----+------------+-------------+
| id | recordDate | temperature |
+----+------------+-------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+----+------------+-------------+
(Source: Leetcode)
I want to get a table containing data with higher temperatures compared to its previous dates (yesterday).
so, I performed this mysql query.
WITH cte AS (SELECT *
FROM Weather w1
ORDER BY w1.recordDate)
SELECT c1.*, c2.*
FROM cte c1
JOIN cte c2 ON c1.Id = c2.Id+1
But it gives me this Output which I was not expecting.
| id | recordDate | temperature | id | recordDate | temperature |
| -- | ---------- | ----------- | -- | ---------- | ----------- |
| 2 | 2015-01-02 | 25 | 1 | 2015-01-01 | 10 |
| 3 | 2015-01-03 | 20 | 2 | 2015-01-02 | 25 |
| 4 | 2015-01-04 | 30 | 3 | 2015-01-03 | 20 |
I was expecting this output for above query.
| id | recordDate | temperature | id | recordDate | temperature |
| -- | ---------- | ----------- | -- | ---------- | ----------- |
| 1 | 2015-01-01 | 10 | 2 | 2015-01-02 | 25 |
| 2 | 2015-01-02 | 25 | 3 | 2015-01-03 | 20 |
| 3 | 2015-01-03 | 20 | 4 | 2015-01-04 | 30 |
Could somebody please help me understand why this happend?
2
Answers
It make sense because c1.id(2) = c2.id(1)+1
Your join (
JOIN cte c2 ON c1.Id = c2.Id+1
) says:Look in C2 for records where the ID is the same as C1 + 1.
So, if C1 ID is 1, it is looking in C2 for 2.
That’s why you get this result.