Tuesday, January 18, 2022

[FIXED] How to find and match data between columns and put in a new column in sql?

Issue

I have sQL database file in which in a table I have different columns. All column values are in numeric e.g. 1,2,4,12,15, etc. Column 4 is empty. I want to pick a values (one by one) from column-3 and find it in column-2, if it matches in then look in column-1 in the same row and pick value from column-1 and insert it in column-4.

If value of column 3 not matches with column 2 then skip it.

enter image description here

Find here screenshot to understand exact problem.


Solution

You can achieve this by joining the table to itself using MySQL JOIN

UPDATE tbl_name t1
JOIN tbl_name t2
ON t1.column3 = t2.column2
SET t1.column4 = t2.column1;

Output

column1     column2     column3     column4
   1          1           2           2
   2          2           3          
   3          5           4         
   4          6           6           4
   5          7           8           6
   6          8          12         
   7         10          11         
   8         14          13         
   9         15          14           8
  10         16          15           9
  11         18          16          10
  12         20          19         
  13         22          20          12
  14         23          25         
  15         24          26         

Here's the working example



Answered By - Samir

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.