SQL从表中获取相关对象不符合条件的记录

时间:2013-09-05 21:19:09

标签: sql join

SELECT  PRH.prid,  PRH.CreationDate, PRH.ClosedDate, PRA.creationdate
FROM PRHeader PRH
left join  PRAction PRA on PRH.PrId =  PRA.PrId
WHERE 
PRA.CreationDate =
(select min(CreationDate  )  from PRAction pa  WHERE  PRH.prid=pa.prid 
 and pa.ActionTypeId<>4)

好的,我不确定如何解释这个...... 但是我有一个带有对象的表PRHeader PRHeader中的每个对象在PRAction中都有0个相关的动作。 上面的代码为每个具有相关actiontype的对象获取最早的操作,因为我想要那个时间戳。 问题是某些对象没有任何符合此条件的操作,然后我仍然希望返回该对象,但将null作为操作时间。 显然我只想要每个对象一次。 有什么建议吗?

非常感谢Gordon Linoff! 这非常有效!

2 个答案:

答案 0 :(得分:3)

您可以将where条件移动到from子句中,您可以left outer join。一种方法是将条件放在on子句中:

SELECT  PRH.prid,  PRH.CreationDate, PRH.ClosedDate, PRA.creationdate
FROM PRHeader PRH left join 
     PRAction PRA
     on PRH.PrId = PRA.PrId and
        PRA.CreationDate = (select min(CreationDate)
                            from PRAction pa 
                            WHERE  PRH.prid = pa.prid and pa.ActionTypeId<>4
                           );

另一种方法是将其作为join条件:

select  PRH.prid,  PRH.CreationDate, PRH.ClosedDate, pa.creationdate
from PRHeader PRH left join
     (select prid, min(CreationDate)
      from PRAction pa 
      where pra.ActionTypeId <> 4
      group by prid
     ) pa
     on PRH.prid = pa.prid;

最后,如果您不想进行聚合,可以将字段计算移到select子句:

select PRH.prid, PRH.CreationDate, PRH.ClosedDate,
       (select min(CreationDate)
        from PRAction pa 
        where  PRH.prid = pa.prid and pa.ActionTypeId <> 4
       ) as CreationDate
from PRHeader PRH;

虽然这看起来像聚合,但引擎应该能够直接使用PRAction(prid, CreationDate)上的索引。您可以通过创建子查询来使这更明显(使用MySQL语法):

       (select CreationDate
        from PRAction pa 
        where PRH.prid = pa.prid and pa.ActionTypeId <> 4
        order by CreationDate
        limit 1
       ) as CreationDate

答案 1 :(得分:0)

您可以在问题中尝试左连接,但可以加入嵌套查询。我想它会是这样的:

SELECT PRH.prid, PRH.CreationDate, PRH.ClosedDate, PRA.creationdate
  FROM PRHeader PRH
  left outer join  (
       SELECT * 
         FROM PRAction pa
        WHERE pa.CreationDate = (
              SELECT min(pa2.CreationDate)
                FROM PRAction pa2
               WHERE pa.prid=pa2.prid 
                 AND pa2.ActionTypeId<>4)
             ) PRA on PRH.PrId =  PRA.PrId