【问题标题】:How join 2 table如何加入2个表
【发布时间】:2018-05-04 19:41:26
【问题描述】:

我有麻烦。如何加入2表查询。 if 数据表:

表 1: 客户 ID : 1,2,3,4,5

客户代码:cus1,cus9,cus4,null,null

客户名称:roya,almudena,jack,jane, Francisco

表 2: 客户 ID : 1,2,3,4

客户代码:cus1,cus2,cus9,null

客户名称:roya,jose,almudena,jane

问:什么是查询以显示 2 个表中的所有名称(无重复名称)。

感谢您的回答。

【问题讨论】:

  • 使用 union all 函数

标签: sql sql-server database tsql


【解决方案1】:

您不需要JOIN,您需要UNION 声明

select distinct name from table1
union
select distinct name from table2

如果您使用union all,它将创建重复项,但union 本身不会。

如果您想更加安全,也可以将其包裹在 select distinct name from () 中。

【讨论】:

  • 感谢您的回答?
  • Mr.Alan 可以再问一个问题吗?什么是从 2 个表中仅显示名称 Jose(表 2)和 Francisco(表 1)的查询?
  • 你应该问一个新问题,但如果我理解正确的话,答案是select distinct name from table1 where name = 'Francisco' union select distinct name from table2 where name = 'Jose'. 请注意这对你有什么帮助。
  • distinct 是不需要的,因为没有allunion 会做同样的事情。在这种情况下,“额外安全”(外部查询)是无稽之谈——你要么得到正确的结果,要么添加相同功能的层只会让代码更加混乱。
【解决方案2】:

如果您在每个表中没有重复的名称(如在您的示例数据中),我强烈建议:

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

这应该有更好的性能。

【讨论】:

    【解决方案3】:

    使用联合声明:

    select distinct Customername from table1
    union
    select distinct Customername from table2
    

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 2023-03-12
      • 2022-01-20
      • 2012-05-24
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      • 2022-11-06
      • 2020-12-25
      相关资源
      最近更新 更多