SQL子查询 - 引用子查询的'WHERE'子句中的外部值

时间:2015-05-17 01:15:22

标签: sql

我正在为学校创建一个IT服务管理系统。我需要从SQL数据库中检索一个查询,该查询显示设备的基本详细信息,以及分配给该设备的所有者的ID。 “设备”表列出了所有计算机,“分配”表指定了为每个设备分配的用户(基于assetID)。

问题是我不确定如何从主查询中引用当前行的'assetID'值。

SELECT 
devices.assetID, 
devices.make, 
devices.model,
TotalServices=Count(services.id),
AssignedOwner=(SELECT assignments.studentID FROM devices INNER JOIN assignments ON devices.assetID=assignments.assetID WHERE assignments.assetID=<VALUE OF ASSET ID FOR CURRENT ROW>)

FROM devices 

LEFT JOIN services 
ON services.assetID = devices.assetID 

GROUP BY 
devices.assetID, 
devices.make, 
devices.model

我不确定如何引用当前行的assetID值以检索指定用户的ID ...

assignments.assetID=<VALUE OF ASSET ID FOR CURRENT ROW>

提前感谢任何指导!

2 个答案:

答案 0 :(得分:1)

我想你想在分配表中添加一个连接,比如:

select      devices.assetid,
            devices.make,
            devices.model,
            count(services.id) as totalservices,
            assignments.studentid as assignedowner
from        devices
  left join assignments
         on devices.assetid = assignments.assetid
  left join services
         on services.assetid = devices.assetid
 group by   devices.assetid,
            devices.make,
            devices.model,
            assignments.studentid

仅当设备可能分别在left joinleft outer join表上没有相应的资产时,才需要assignmentsservices(同样的事情)。如果资产总是在其他表上有一个值(独立考虑每个表),则应将left join更改为join

答案 1 :(得分:0)

如果我理解正确,这不是你要找的东西吗?

SELECT 
devices.assetID, 
devices.make, 
devices.model,
TotalServices=Count(services.id),
assignments.studentID AS AssignedOwner

FROM devices 

INNER JOIN assignments ON devices.assetID=assignments.assetID

LEFT JOIN services 
ON services.assetID = devices.assetID 

GROUP BY 
devices.assetID, 
devices.make, 
devices.model

您是否拥有要测试的预期结果的示例数据?