PHP - 从不同的SQL数据库加入字段时出错

时间:2015-06-04 15:55:49

标签: php sql sql-server select join

我正在尝试构建一个查询,其中我返回来自3个不同表的结果,如下所示:

事件表 DateTime,Direction,DeviceName

租户租户名称

个人 FirstName,LastName

最初,我使用以下SQL返回前2个表中的字段:

SELECT EventTime, DeviceName, Comment, TenantName
FROM taclogdata.dbo.Event 
     INNER JOIN InetDb.dbo.Tenants 
       ON taclogdata.dbo.Event.Tenant = InetDb.dbo.Tenants.TenantId
WHERE taclogdata.dbo.Event.EventTime 
       BETWEEN '01/04/2014 16:00:00' AND '01/04/2014 16:00:59

我已使用 TenantId 字段加入了活动和租户表。

然后我还需要返回字段 FirstName LastName (来自Individuals表),所以我尝试使用下面的sql:

    SELECT EventTime, DeviceName, Comment, TenantName, FirstName, LastName 
    FROM taclogdata.dbo.Event 
    INNER JOIN InetDb.dbo.Tenants 
       ON taclogdata.dbo.Event.Tenant = InetDb.dbo.Tenants.TenantId
    INNER JOIN InetDb.dbo.Tenants
       ON inet.dbo.Tenants.TenantId = inet.dbo.Individuals.TenantNdx
    WHERE taclogdata.dbo.Event.EventTime 
          BETWEEN '01/04/2014 16:00:00' AND '01/04/2014 16:00:59'

然而,这返回了以下错误:

  

对象" InetDb.dbo.Tenants"和" InetDb.dbo.Tenants"在FROM   子句具有相同的暴露名称。使用相关名称   区分他们。

有人可以指导我如何解决这个问题吗?

已更新

我已将语法修改为以下内容:

SELECT EventTime, DeviceName, Comment, TenantName, FirstName, LastName 
FROM taclogdata.dbo.Event 
INNER JOIN InetDb.dbo.Tenants 
    ON taclogdata.dbo.Event.Tenant = InetDb.dbo.Tenants.TenantId
INNER JOIN InetDb.dbo.Individuals
    ON  InetDb.dbo.Tenants.TenantId = InetDb.dbo.Individuals.TenantNdx
WHERE taclogdata.dbo.Event.EventTime 
      BETWEEN '01/04/2014 16:00:00' AND '01/04/2014 16:00:59'

然后我收到以下错误:

  

消息209,级别16,状态1,行1不明确的列名称' FirstName'。   消息209,级别16,状态1,行1不明确的列名称'姓氏'

1 个答案:

答案 0 :(得分:1)

您在INNER JOIN中缺少Individuals表,并错误地使用Tenants

SELECT EventTime, DeviceName, Comment, TenantName,        
       InetDb.dbo.Individuals.FirstName, InetDb.dbo.Individuals.LastName 
FROM taclogdata.dbo.Event 
INNER JOIN InetDb.dbo.Tenants 
    ON taclogdata.dbo.Event.Tenant = InetDb.dbo.Tenants.TenantId
INNER JOIN InetDb.dbo.Individuals
    ON  InetDb.dbo.Tenants.TenantId = InetDb.dbo.Individuals.TenantNdx
WHERE taclogdata.dbo.Event.EventTime 
       BETWEEN '01/04/2014 16:00:00' AND '01/04/2014 16:00:59'