将 2 个表合并为 1

Join 2 tables into 1

我有一个客户和 Customer_2 table,我想将其合并:

两个 table 中都有数据,但是在使用语句连接时,只返回列名而没有数据。我正在尝试使用以下连接语句:

select distinct * 
from Customer c 
join Customer_2 d on c.CUST_NUM = d.CUST_NUM  

这些是 table:

CREATE TABLE [Customer] 
(
  [CUST_NUM] [INT] NOT NULL,
  [CUST_LNAME] [VARCHAR](50) NULL,
  [CUST_FNAME] [VARCHAR](50) NULL,
  CUST_BALANCE [MONEY] NOT NULL,
) 
ON [PRIMARY]

CREATE TABLE [Customer_2]  
(
  [CUST_NUM] [INT] NOT NULL,
  [CUST_LNAME] [VARCHAR](50) NULL,
  [CUST_FNAME] [VARCHAR](50) NULL,
) 
ON [PRIMARY]

每个Table中的数据:

INSERT INTO Customer 
VALUES 
('1000', 'Smith', 'Jeanne', '1050.11'),
('1001', 'Ortega', 'Juan', '840.92');

INSERT INTO CUSTOMER_2 
VALUES 
('2000', 'McPherson', 'Anne'),
('2001', 'Ortega', 'Juan'),
('2002', 'Kowalski', 'Jan'),
('2003', 'Chan', 'George');

预期输出将 customer_2 合并到客户 table 的底部,对于客户 2 [ 的四个客户中的每一个,额外的列 CUST_BALANCE 为 0 或 null table。所需的输出还应排除 Juan Ortega 的第二个条目或 CUSTOM_NUM 是 2001

您可以使用 UNION ALL 进行此操作。即:

select cust_num, cust_fname, cust_lname, balance from Customer
union all 
select cust_num, cust_fname, cust_lname, 0 from Customer_2 c2
where not exists (select * from Customer c 
       where c.cust_fname = c2.cust_fname and c.cust_lname = c2.cust_lname);

DBFiddle demo

PS: 可能不是官方术语而是join,垂直连接表,而union [all] 水平连接。

另一种选择

只需在 2 个表中使用完全外部联接。

您将从两个表中获得所有共同和不共同的行。

https://www.w3schools.com/sql/sql_join_full.asp