SQL在内连接的中间使用嵌套选择

时间:2010-09-09 18:33:19

标签: sql sql-server sql-server-2005

是否可以在加入过程中使用选择...

我正在尝试执行以下操作:

FROM 
tblorders o 
INNER JOIN tblunits u on o.id = u.orderid
INNER JOIN ((SELECT
                   ,Min(n.date) as [MinDate]
              from tblNotes n
             Where n.test = 'test') te
INNER JOIN tblnotes n on te.id = n.id
                     and te.[MinDate] = n.AuditinsertTimestamp)
INNER Join tblClient c ON o.ClientId = c.Id

基本上在查询中间的选择中,它只选择带有最小日期的音符。问题是我需要在这里做这个,因为我需要从tblOrders成为第一个表.......

建议?

3 个答案:

答案 0 :(得分:6)

INNER JOIN失败,因为你在这里有一个引导逗号:

,Min(n.date) as [MinDate]

我认为你正在寻找这样的东西:

SELECT ...
FROM tblorders o   
INNER JOIN tblunits u on o.id = u.orderid  
INNER JOIN (
    SELECT id, Min(date) as [MinDate]  
    from tblNotes 
    Where test = 'test'  
    group by id
) te  <-- not sure what JOIN clause to use here, please post schema
INNER JOIN tblnotes n on te.id = n.id  
    and te.[MinDate] = n.AuditinsertTimestamp  
INNER Join tblClient c ON o.ClientId = c.Id  

答案 1 :(得分:2)

您缺少别名和加入条件:

FROM 
tblorders o 
INNER JOIN tblunits u on o.id = u.orderid
INNER JOIN ((SELECT Min(n.date) as [MinDate]
              from tblNotes n
             Where n.test = 'test') te
INNER JOIN tblnotes n on te.id = n.id
                     and te.[MinDate] = n.AuditinsertTimestamp)
-- missing
AS z
ON <join conditions haere>
INNER Join tblClient c ON o.ClientId = c.Id

答案 2 :(得分:-1)

是的,您可以选择加入。