如何根据ID从SQL表中检索数据?

时间:2016-02-02 00:53:33

标签: sql-server

我正在努力熟悉规范化,并且我遇到了一个问题,因为我试图将三个表连接起来创建一个大规模的SELECT,它将提供有关TCustomers中人员的所有信息表,但我不确定如何这样做。这是我的表结构:

CREATE TABLE TCustomers (
     CustomerID     INT             IDENTITY(1,1)   NOT NULL
    ,FirstName      VARCHAR(50)     NOT NULL
    ,LastName       VARCHAR(50)     NOT NULL
    ,City           VARCHAR(50)     NOT NULL
    ,[State]        VARCHAR(50)     NOT NULL
    ,ZipCode        VARCHAR(50)     NOT NULL
    ,EmailAddress   VARCHAR(50)     NOT NULL
    ,CONSTRAINT pkCustomers PRIMARY KEY (CustomerID)
);

CREATE TABLE TLocations (
     LocationID     INT             NOT NULL
    ,LocationName   VARCHAR(50)     NOT NULL
    ,CONSTRAINT pkLocations PRIMARY KEY (LocationID)
);

CREATE TABLE TBenefitLevels (
     BenefitLevelID     INT             NOT NULL
    ,BenefitLevelName   VARCHAR(50)     NOT NULL 
    ,CONSTRAINT pkBenefitLevels PRIMARY KEY (BenefitLevelID)
);

CREATE TABLE TCustomerLocationBenefits (
     CustomerID     INT             NOT NULL
    ,LocationID     INT             NOT NULL
    ,BenefitLevelID INT             NOT NULL
    ,CONSTRAINT pkCustomerLocationBenefits PRIMARY KEY (CustomerID, LocationID)
);

CREATE TABLE TCustomerStatus (
     CustomerID         INT             NOT NULL
    ,FirstOrderDate     DATE            NOT NULL
    ,NewestOrderDate    DATE            NOT NULL         
    ,CONSTRAINT pkCustomerStatus PRIMARY KEY (CustomerID)
);

我正在尝试创建一个SELECT语句,它将从TCustomers中获取FirstName,LastName,City,[State],ZipCode和EmailAddress,BenefitLevelName基于TBenefitLevels中每个客户的BenefitLevelID,LocationName基于来自TLocations的每个客户的LocationID。我知道这是可能的,但我完全忘记了怎么做,这是我当前的SELECT语句,它获取必要的ID,但不是名称:

SELECT TC.FirstName, TC.LastName, TC.City, TC.[State], TC.ZipCode, TC.EmailAddress, TL.LocationName, TBL.BenefitLevelName, TCS.FirstOrderDate, TCS.NewestOrderDate
FROM  TCustomers AS TC
     ,TLocations AS TL
     ,TBenefitLevels AS TBL
INNER JOIN TCustomerStatus AS TCS ON TC.CustomerID = TCS.CustomerID
INNER JOIN TCustomerLocationBenefits AS TCLB ON TC.CustomerID = TCLB.CustomerID

目前我收到的错误是"多部分标识符" TC.CustomerID"无法受约束。如果我删除TLocations和TBenefitLevels,并用TCLB中的各自ID替换TL.LocationName和TBL.BenefitLevelName,它确实有效,但不是我想要的方式。

请帮忙!

1 个答案:

答案 0 :(得分:1)

看起来TCustomerLocationBenefits就是我所说的桥接表,即映射表或关系表,因为它包含所有三个实体之间的关系:客户,位置和利益级别。

要解决此类问题,您通常会从此表开始,因为它会驱动查询的连接。

查看下面的查询是否返回您要查看的内容:

select b.FirstName, b.LastName, b.City, b.State, b.ZipCode, b.EmailAddress
    , c.BenefitLevelName
    , d.LocationName
from TCustomerLocationBenefits a
join TCustomers b                   on a.CustomerID = b.CustomerID
join TBenefitLevels c               on a.BenefitLevelID = c.BenefitLevelID
join TLocations d                   on a.LocationID = d.LocationID