我有一个包含4条记录的表格AddressTypes(家庭,办公室,度假,酒店)和一个共享提交的addresstypeid的表格地址。
在地址表中,我有1条“home”类型的记录,我想要一个查询,我得到4行这样:
Type Address1 Address2 City State
home piping 1232 Austin Tx
office null null null null
vacation null null null null
hotel null null null null
以下是表格的图像:http://tinypic.com/view.php?pic=28078xv&s=6
我确信使用交叉连接可能非常容易,但是没有得到它。希望有人能指导我。提前欣赏。
答案 0 :(得分:2)
Left joining AdddressTypes到地址将产生所需的结果:
select at.Type,
a.Address1,
a.Address2,
a.City,
a.State
from AddressTypes at
left join Address a
on at.AddressTypeID = a.AddressTypeID
-- For this query to make sense
-- Filter one person only
and a.PersonID = @PersonID
----------- VAAA已添加此部分------------------------
尼古拉,我改变了这个:
select at.description,
a.Address1,
a.Address2,
a.City
from address_types at
left join Address a
on 1 = 1
-- For this query to make sense
-- Filter one person only
and a.addressid = 24
然后我获得了4行,但是所有这些行都有相同的地址信息,而“home”类型地址就是带有数据的地址。所以它的关闭......
答案 1 :(得分:0)
使用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