根据ID SQL选择查询显示相应的名称

时间:2017-05-05 19:02:48

标签: sql-server select subquery

我有2张桌子

tbl_jobs

CREATE TABLE [dbo].[tbl_jobs]
(
    [JobID] [int] IDENTITY(1,1) NOT NULL,
    [JobType] [nvarchar](50) NOT NULL,
    [RequestID] [int] NOT NULL,
    [AssignTo] [int] NOT NULL,
    [FromOrgID] [int] NOT NULL,
    [ToOrgID] [int] NOT NULL,
    [Ammount] [nvarchar](50) NOT NULL,
    [JobStatus] [nvarchar](50) NOT NULL,
    [Remark] [nvarchar](50) NULL,
    [strOwner] [nvarchar](50) NOT NULL,
    [dbTstamp] [datetime2](7) NOT NULL,

    CONSTRAINT [PK_tbl_jobs] 
        PRIMARY KEY CLUSTERED ([JobID] ASC)
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[tbl_jobs] WITH CHECK 
    ADD CONSTRAINT [FK_tbl_jobs_tbl_orgs] 
    FOREIGN KEY([FromOrgID]) REFERENCES [dbo].[tbl_orgs] ([OrgID])
GO

ALTER TABLE [dbo].[tbl_jobs] CHECK CONSTRAINT [FK_tbl_jobs_tbl_orgs]
GO

ALTER TABLE [dbo].[tbl_jobs]  WITH CHECK 
    ADD CONSTRAINT [FK_tbl_jobs_tbl_orgs1] 
    FOREIGN KEY([ToOrgID]) REFERENCES [dbo].[tbl_orgs] ([OrgID])
GO

tbl_orgs

CREATE TABLE [dbo].[tbl_orgs]
(
    [OrgID] [int] IDENTITY(1,1) NOT NULL,
    [OrgName] [nvarchar](50) NOT NULL,
    [OrgTele] [nvarchar](50) NULL,
    [OrgEmail] [nvarchar](50) NULL,
    [OrgArea] [nvarchar](50) NOT NULL,
    [OrgCity] [nvarchar](50) NOT NULL,
    [OrgLocation] [nvarchar](50) NOT NULL,
    [OrgType] [nvarchar](50) NOT NULL,
    [OrgStatus] [nvarchar](50) NOT NULL,
    [strOwner] [nvarchar](50) NOT NULL,
    [dbTStamp] [datetime2](7) NOT NULL,

    CONSTRAINT [PK_tbl_orgs] 
        PRIMARY KEY CLUSTERED ([OrgID] ASC)
) ON [PRIMARY]
GO

我需要获取大多数tbl_jobs列以及相应的tbl_orgs.OrgName tbl_jobs.FromOrgID& tbl_jobs.ToOrgID

如果我选择tbl_orgs.orgname,我就无法获得正确的结果。

我被困在这里。我应该使用什么类型的查询来获得结果。?

enter image description here

1 个答案:

答案 0 :(得分:1)

您要加入两次同一个表实例。您应该单击“添加表”并再次添加tbl_orgs并将“FromOrgID”连接到它的一个实例,将“ToOrgID”连接到另一个实例。否则,除非“FromOrgID”和“ToOrgID”相等,否则连接没有意义。