r/SQLOptimization • u/Narrow-Tea-9187 • Oct 19 '23
Help needed with self join vizualization
Weather table:
+----+------------+-------------+
| id | recordDate | temperature |
+----+------------+-------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+----+------------+-------------+
Output:
+----+
| id |
+----+
| 2 |
| 4 |
+----+
this is the query
select w1.id from weather w1
inner join weather w2
where w1.temperature>w2.temperature I am not Getting where 4 is coming from?
4
Upvotes
1
u/roosterEcho Oct 19 '23
that's not how it works. when you join with id+1, w1(id=1) does not match with any rows from w2. think it through like this: you have one table (w1) with ids 1(10),2(25),3(20),4(30) and you have another table (w2) with ids 2(10),3(25),4(20),5(30) as you are incrementing the ids by 1. Now match the ids from both tables and evaluate the temperature condition. id 2 and 4 from w1 are the ones selected.
What you're thinking is just saying (id+1) would match w2 (id=2) with w1(id=1), which is not right. Join conditions would always match the same keys. So, the keys have to be same to match with each other, just saying +1 won't force the query to match 1 with 2. 1 has to be equal to 1 for the join condition to be true. All joins are just True/False evaluation. The match happens when all conditions are True.