【问题标题】:Join two tables and combine the same fields using another field in one table and remaining fields as it is连接两个表并使用一个表中的另一个字段和其余字段原样组合相同的字段
【发布时间】:2017-08-19 09:03:01
【问题描述】:

我有两个表(table1table2),它们都有一个共同的列(field1)。我需要加入两个表。然后将 field1 内容命名为 table1 中的另一列内容 (field2),其余的 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

【问题讨论】:

  • 你在做什么?显示尝试
  • 并将表格显示为其结构,而不是“免费故事”
  • 我的叙述是为了让别人理解。
  • 这是我正在尝试的问题的一部分,要解释所有问题非常复杂,所以只发布了其中的一部分

标签: sql-server join case


【解决方案1】:

检查这个 -

 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

【讨论】:

    【解决方案2】:

    只需使用临时表变量来存储连接查询结果并将临时表数据与 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
    

    【讨论】:

    • 这是一个很好的解决方案,但不应更新列内容,它们应使用 select 语句与其他列内容进行别名。 case when field1 in table1 then field2 else field1(表2中的剩余值)end
    • 您只需要更新临时变量表​​中的列值,而不是常规表。
    • @YogeshSharma 任何自定义硬编码都太糟糕了。如果您有where field1 in ('cat', 'dog', 'camel') 数千个值怎么办?不是这样。
    • @AliaksandrBortnik 只在 field1 中使用 select 语句
    【解决方案3】:

    描述不清楚,但我想是这样。

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      相关资源
      最近更新 更多