首页 > 解决方案 > 替换几个条目

问题描述

我有两个相似的表,它们具有相同的列和相同类型的数据。目标是获取 table_a 的数据,但如果存在具有相同 id 的值,则将所有条目替换为 table_b 值。

所以我有以下两个选择:

SELECT table_a.id, table_a.text

SELECT table_b.id, table_b.text

在伪代码中:

iterate table_a data
    if table_a.id == table_b.id then
        table_out.id = table_b.id
        table_out.text = table_b.text
    else
        table_out.id = table_a.id
        table_out.text = table_a.text
    end if
end iterate

表table_a 和table_b 的数据不应被触及。只有选择的输出应包含数据。

我首先考虑用左连接连接两个表。然后我需要一种 if 来切换选择的列。

谢谢你。

标签: mysqlsql

解决方案


coalesce()为此,我建议:

select a.id,
       coalesce(b.text, a.text) as text
from table_a a left join
     table_b b
     on a.id = b.id
order by a.id;

推荐阅读