使用 LEFT OUTER JOIN,它返回来自左右表的匹配记录的一份副本以及来自两个表的不匹配记录。这是我尝试的测试代码:
CREATE TABLE AddressTypes(
AddressType SMALLINT NOT NULL,
[Description] NVARCHAR(50))
ALTER TABLE AddressTypes
ADD CONSTRAINT PK_AddressTypes_AddressType
PRIMARY KEY (AddressType)
CREATE TABLE [Address] (
AddressID INT NOT NULL,
AddressType SMALLINT,
Address1 NVARCHAR(50),
Address2 NVARCHAR(50),
City NVARCHAR(50),
State CHAR(2))
ALTER TABLE [Address]
ADD CONSTRAINT PK_Address_AddressID
PRIMARY KEY (AddressID)
ALTER TABLE [Address]
ADD CONSTRAINT FK_address_addresstypes_addresstype
FOREIGN KEY (AddressType) REFERENCES AddressTypes(AddressType)
INSERT INTO AddressTypes VALUES (1, 'home'), (2, 'office'),
(3, 'vacation'), (4, 'hotel')
INSERT INTO address VALUES (1, 1, 'piping', '1232', 'Austin', 'TX')
-- Here is the query that outputs the result set.
SELECT AT.AddressType AS [Type], A.Address1, A.Address2, A.City, A.State
FROM AddressTypes AT
LEFT OUTER JOIN address A
ON AT.AddressType = A.AddressType