我有一个试图连接在一起的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]
每个表中的数据:
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 2表上的四个客户中的每一个,额外的列CUST_BALANCE
为0或为空。
select c.[CUST_NUM] , c.[CUST_BALANCE]
FROM INVOICE I
JOIN (
SELECT CUST_NUM, CUST_BALANCE FROM Customer c
UNION
SELECT CUST_NUM, NULL as CUST_BALANCE FROM Customer_2 d
) tbl t on i.cust_num = t.cust_num
我想发生了什么事,就是您的联接条件从未得到满足,这意味着两个表都没有相同的cust_name
尝试按以下左联接进行调试
select distinct *
from Customer c
Left join Customer_2 d on
c.CUST_NUM =
d.CUST_NUM
您可以将Customer
和Customer_2
与UNION ALL
合并。您可以将此数据集与INNER JOIN
合并以获取每张发票的客户数据:
SELECT *
FROM INVOICE INNER JOIN (
SELECT CUST_NUM, CUST_LNAME, CUST_FNAME, CUST_BALANCE FROM Customer
UNION ALL
SELECT CUST_NUM, CUST_LNAME, CUST_FNAME, NULL FROM Customer_2
) CUSTOMER ON INVOICE.CUST_NUM = CUSTOMER.CUST_NUM
您还可以在SO上检查此问题:What is the difference between JOIN and UNION?