File tree Expand file tree Collapse file tree 3 files changed +45
-0
lines changed
sql-queries-12/updating-rows-subquery-referencing-same-table Expand file tree Collapse file tree 3 files changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ -- Using a Self Join
2
+ UPDATE Program AS P1
3
+ JOIN (
4
+ SELECT id, DATE_ADD(start_date, INTERVAL 3 WEEK) AS new_end_date
5
+ FROM Program
6
+ ) AS P2
7
+ ON P1 .id = P2 .id
8
+ SET P1 .end_date = P2 .new_end_date ;
9
+
10
+ -- Using a Derived Table
11
+ UPDATE Program
12
+ SET end_date = (
13
+ SELECT new_end_date FROM (
14
+ SELECT DATE_ADD(start_date, INTERVAL 3 WEEK) AS new_end_date
15
+ FROM Program AS Temp
16
+ WHERE Temp .id = Program .id
17
+ ) AS Temp_table
18
+ );
Original file line number Diff line number Diff line change
1
+ -- Self-join
2
+ UPDATE Program AS P1
3
+ SET end_date = P2 .start_date + INTERVAL ' 3 weeks'
4
+ FROM Program AS P2
5
+ WHERE P1 .id = p2 .id ;
6
+
7
+ -- Subquery within UPDATE ... SET
8
+ UPDATE Program
9
+ SET end_date = (
10
+ SELECT start_date + INTERVAL ' 3 weeks'
11
+ FROM Program AS Temp
12
+ WHERE Temp .id = Program .id
13
+ );
Original file line number Diff line number Diff line change
1
+ -- Self join
2
+ UPDATE P1
3
+ SET P1 .end_date = DATEADD(week, 3 , P2 .start_date )
4
+ FROM Program AS P1
5
+ JOIN Program AS P2
6
+ ON P1 .id = P2 .id ;
7
+
8
+ -- Subquery within UPDATE ... SET
9
+ UPDATE Program
10
+ SET end_date = (
11
+ SELECT DATEADD(week, 3 , start_date)
12
+ FROM Program AS Temp
13
+ WHERE Temp .id = Program .id
14
+ );
You can’t perform that action at this time.
0 commit comments