MySQL:将两行合并为一行?

MySQL: Combine two rows into one row?

如何将同一 table 中的两行合并为一行以避免空字段?例如,如果我有以下两行:

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

我要得到结果:

1 12 74 13

换句话说,我想要 id = 1 行中的值,但如果它有 null 值,我想用行中的相应值替换那些 nulls id = 2。我想另一个约束是这个 table 中的列数很大,所以我想避免列出单独的列。 MySQL 这完全有可能吗?

您可以使用 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