我有一个要结合在一起的Customer和Customer_2表:
两个表中都有数据,但是在加入语句后,仅返回列名而没有数据。我正在尝试使用以下join语句:
select distinct *
from Customer c
join Customer_2 d on c.CUST_NUM = d.CUST_NUM
这些是表格:
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]
每个表中的数据:
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组合到客户表的底部,而对于customer 2表上的四个客户中的每一个,额外的列CUST_BALANCE
为0或为空。期望的输出还应该排除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);
PS:可能不是官方用语,而是连接,垂直连接表,而union [all]水平连接。