加入两个表并使用一个表中的另一个字段和剩余字段组合相同的字段

时间:2017-08-19 09:03:02

标签: sql-server join case

我有两个表(table1table2),两个表都有一个共同的列(field1)。我需要加入两个表。然后将field1内容命​​名为field2中的其他列内容(table1),并保留其余table2内容。

表1:

Field1     Field2
------------------
 cat        pet1
 dog        pet2
 camel      pet3

表2:

field1
--------
cat
dog
camel
lion
tiger
wolf

我的输出应该是

Field1 
------------
pet1
pet2
pet3
lion
tiger
wolf

3 个答案:

答案 0 :(得分:0)

只需使用Temp表变量来存储连接查询结果&将临时表数据与field1交换如下:

insert into temp
select t2.field1, t1.field2 from
(
  select * from table2
)t2
left join table1 t1 on t1.field1 = t2.field1
update temp set field1 = filed 
where field1 in ('cat', 'dog', 'camel')
select field1 from temp

答案 1 :(得分:0)

描述不清楚,但我想是的。

SELECT T2.Field1 as Data
FROM Table2 as T2
LEFT OUTER JOIN Table1 as T1
    ON T1.Field1 = T2.Field2
WHERE T1.Field1 IS NULL
UNION ALL
SELECT Field2 as Data 
FROM Table1;

答案 2 :(得分:0)

检查一下 -

 Select field2 from table1 where field1
    In (select field1 from table2)
    Union 
    Select field1 from table1 where 
    Field1 not in (select field1 from table2)
    Union
    Select field1 from table2 where 
    Field1 not in (select field1 from table1);

SQL Fiddle