简体   繁体   中英

update using self join not returning the results I am looking for

Hi all I need to do a self join that doesn't include the null value.

Create the table:

 CREATE TABLE t2 ( col1 varchar(255), col2 varchar(255), col3 varchar(255), col4 varchar(255), col5 varchar(255), col6 varchar(255) ); --Populate the table: INSERT INTO t1 (col1, col2, col3, col4, col5, col6) VALUES ('1', '', 'new1', 'name1','',''), ('2', '', 'new2', 'name2','oldvalue1',''), ('3', '', 'new3', 'name3','',''), ('4', 'value1', 'new4', 'name4','','') ; --Resulting in: | col1 | col2 | col3 | col4 | col5 | col6 | | 1 | | new1 | name1 | | | | 2 | | new1 | name1 | oldvalue1 | | | 3 | | new1 | name1 | | | | 4 | value1 | new1 | name1 | | | 

My update:

update t2 AS A, t2 AS B
set A.col6 = B.col3
where B.col5 = A.col2;

But the result is:

  | col1 | col2 | col3 | col4 | col5 | col6 | | 1 | | new1 | name1 | | new1 | | 2 | | new1 | name1 | oldvalue1 | new1 | | 3 | | new1 | name1 | | new1 | | 4 | value1 | new1 | name1 | | | 

What I want is:

 | col1 | col2 | col3 | col4 | col5 | col6 | | 1 | | new1 | name1 | | | | 2 | | new1 | name1 | oldvalue1 | new1 | | 3 | | new1 | name1 | | | | 4 | value1 | new1 | name1 | | | 

what am I doing wrong?

I am using myspql and sequelpro on a mac

Thanks!

did you try that ?

update b set b.col6=a.col3 from t2 a inner join t2 b on b.col5 = a.col2

thanks for all the help. I figured out what my issue was. in the table the null cess were just blank they didn't contain "NULL" in them. once i updated the table to have "NULL" in the blank cells then everything worked. thanks again for helping me on my sql journey.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM