0

我有一个包含 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

我确定这很容易,也许使用交叉连接但不明白。希望有人可以指导我。提前欣赏。

4

2 回答 2

2

将 AdddressTypes左连接到 Addresses 将产生所需的结果:

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 行,但它们都具有相同的地址信息,只有“家”类型的地址是带有数据的地址。所以它接近...

于 2012-07-12T22:58:26.303 回答
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
于 2012-07-12T23:40:16.780 回答