简体   繁体   中英

MySQL: Combine two rows into one row?

How do I combine two rows from the same table into one row to avoid null fields? For example, if I have the following two rows:

id col1 col2 col3
 1   12   null 13  
 2   56   74   89

I want to get the result:

1 12 74 13

In another words, I want the values from the row with the id = 1 but if it has null values, I want to replace those null s with corresponding values from the row with id = 2. I guess another constraint is that number of columns in this table is large so I would want to avoid listing the individual columns. Is this at all possible with MySQL?

You can use left join :

select coalesce(t.col1, t2.col1) as col1,
       coalesce(t.col2, t2.col2) as col2,
       coalesce(t.col3, t2.col3) as col3       
from t left join
     t t2
     on t2.id = 2
where t.id = 1

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