sql - 在 SQL Server 中用 2 个表的键替换数据

标签 sql sql-server

我的问题是用 SQL Server 中的键替换。任何人都可以给我一个查询吗?

感谢您的回答!

表 1:

    ID | Code | Des | more columns
    ---+------+-----+-------------
    1  | 100  | a   | ...
    2  | 200  | b   | ...
    3  | 300  |data3| ... 

表 2:

    ID | Code | Des 
    ---+------+------
    1  | 100  | data1   
    2  | 200  | data2   

结果一定是这样的:

    ID | Code | Des | more columns
    ---+------+-----+-------------
    1  | 100  |data1| ...
    2  | 200  |data2| ...
    3  | 300  |data3| ... 

最佳答案

做一个LEFT JOIN,如果没有table2.Des值,取table1.Des代替:

select t1.ID, t1.Code, coalesce(t2.Des, t1.Des), t1.more Column
from table1 t1
left join table2 t2 on t1.code = t2.code

或者,也许你想要这样:

select * from table2
union all
select * from table1 t1
where not exists (select 1 from table2 t2
                  where t2.code = t1.code)

即返回 table2 行,如果代码在 table1 但不在 table2 中,也返回该行。

关于sql - 在 SQL Server 中用 2 个表的键替换数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36715245/

相关文章:

mysql - 如何调整 UNION ALL 查询?

java - 如何在java中从sys.tables获取表名?

sql-server - 在 SQL Server 中获取一周的第一天

java - 我正在尝试从数据库中减去输入文本字段的数字,但不知道该怎么做

sql - 条件的顺序重要吗?

c# - 如何使用 dapper 获取第一个子值(通常查询 count(*) 作为唯一结果)

python - OpenERP/Odoo - 字符串内的引号不起作用 - cr.execute(SQL)

SQL 与 group by 相交

MySQL Workbench 从 SQL Server 2008 迁移到 MySQL : ERROR: Determine number of rows to copy: unsupported operand type(s)

sql - not in 和 in with null 值之间的区别