我有一个试图连接在一起的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 [INVOICE]
(
[Invoice_NUM] [INT] NOT NULL,
[CUST_NUM] [INT] NOT NULL,
[INV_DATE] [SMALLDATETIME] NOT NULL,
[INV_AMOUNT] [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]
Data in each Table:
Insert into Customer values
('1000', 'Smith', 'Jeanne', '1050.11'),
('1001', 'Ortega', 'Juan', '840.92');
Insert into INVOICE values
('8000', '1000', '2016-03-23', '235.89'),
('8001', '1001', '2016-03-23', '312.82'),
('8002', '1001', '2016-03-30', '528.10'),
('8003', '1000', '2016-04-12', '194.78'),
('8004', '1000', '2016-04-23', '619.44');
Insert into CUSTOMER_2 values
('2000', 'McPherson', 'Anne'),
('2001', 'Ortega', 'Juan'),
('2002', 'Kowalski', 'Jan'),
('2003', 'Chan', 'George');
预期的输出将customer_2组合到customer表的底部,而对于customer 2表的四个客户中的每一个,额外的列CUST_BALANCE为0或为空。
非常感谢您的帮助
我猜发生了什么事,您的连接条件从未得到满足,这意味着两个表具有相同的cust_name尝试调试为不相等
select distinct *
from Customer c
join Customer_2 d on c.CUST_NUM <>
d.CUST_NUM
select c.[CUST_NUM] , c.[CUST_BALANCE]
from Customer c
join Customer_2 d on c.CUST_NUM = d.CUST_NUM
您可以使用以下内容。我假设您想合并Customer
和Customer2
并加入Invoice
:
SELECT *
FROM INVOICE i INNER JOIN (
SELECT CUST_NUM, CUST_LNAME, CUST_FNAME, CUST_BALANCE FROM Customer
UNION ALL
SELECT CUST_NUM, CUST_LNAME, CUST_FNAME, NULL FROM Customer2
) Customer c ON i.CUST_NUM = c.CUST_NUM