多表Selfjoins - 有一个很好的方法吗?

时间:2012-12-13 22:33:01

标签: tsql sql-server-2005 self-join

我试图使用此查询从数据库中提取一些信息,

SELECT dbo.AfterHoursParameterSetup.Customer_id
, dbo.tblCustomer.Company
, dbo.tblDevices.device_id
, dbo.AfterHoursParameterSetup.DeviceMasterID
, dbo.tblDriverType.DriverType
, dbo.tblGroups.GroupName
, dbo.AfterHoursParameterSetup.ReportBy
, dbo.AfterHoursParameterSetup.TripTimeFilter
, dbo.AfterHoursParameterSetup.chkWeekEndTravel
, dbo.AfterHoursParameterSetup.WeekdayStart
, dbo.AfterHoursParameterSetup.WeekDayEnd
, dbo.AfterHoursParameterSetup.WeekEndFrom
, dbo.AfterHoursParameterSetup.WeekEndTo
, dbo.AfterHoursParameterSetup.ReportType
FROM dbo.AfterHoursParameterSetup
FULL JOIN dbo.tblCustomer
ON dbo.AfterHoursParameterSetup.Customer_id = dbo.tblCustomer.Customer_id
FULL JOIN dbo.tblDriverType
ON dbo.AfterHoursParameterSetup.DeviceMasterID = dbo.tblDriverType.DriverType_id
FULL JOIN dbo.tblGroups
ON dbo.AfterHoursParameterSetup.DeviceMasterID = dbo.tblGroups.Group_id
FULL JOIN dbo.tblDevices
ON dbo.AfterHoursParameterSetup.DeviceMasterID = dbo.tblDevices.device_id
ORDER BY dbo.AfterHoursParameterSetup.Customer_id ASC

是否有另一种方法来构造此查询,以便我可以消除NULL值? dbo.AfterHoursParameterSetup.DeviceMasterID将所有内容链接在一起,但该列使用来自三个不同表的值,因此在没有匹配值的情况下,它会为所有其他没有匹配连接值的列返回NULL。

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你需要交叉表。如果是这样的用户内部联接。

SELECT dbo.AfterHoursParameterSetup.Customer_id
    , dbo.tblCustomer.Company
    , dbo.tblDevices.device_id
    , dbo.AfterHoursParameterSetup.DeviceMasterID
    , dbo.tblDriverType.DriverType
    , dbo.tblGroups.GroupName
    , dbo.AfterHoursParameterSetup.ReportBy
    , dbo.AfterHoursParameterSetup.TripTimeFilter
    , dbo.AfterHoursParameterSetup.chkWeekEndTravel
    , dbo.AfterHoursParameterSetup.WeekdayStart
    , dbo.AfterHoursParameterSetup.WeekDayEnd
    , dbo.AfterHoursParameterSetup.WeekEndFrom
    , dbo.AfterHoursParameterSetup.WeekEndTo
    , dbo.AfterHoursParameterSetup.ReportType
FROM dbo.AfterHoursParameterSetup 
    INNER JOIN dbo.tblCustomer ON dbo.AfterHoursParameterSetup.Customer_id = dbo.tblCustomer.Customer_id
    INNER JOIN dbo.tblDriverType ON dbo.AfterHoursParameterSetup.DeviceMasterID = dbo.tblDriverType.DriverType_id
    INNER JOIN dbo.tblGroups ON dbo.AfterHoursParameterSetup.DeviceMasterID = dbo.tblGroups.Group_id
    INNER JOIN dbo.tblDevices ON dbo.AfterHoursParameterSetup.DeviceMasterID = dbo.tblDevices.device_id
ORDER BY dbo.AfterHoursParameterSetup.Customer_id ASC