从Query中的第二个表中获取值

时间:2017-10-07 13:00:39

标签: sql sql-server sql-server-2012

select * 
from EFLOVRelationship R 
where R.parentEFLOVValueId = '5320' 
  and R.childEFLOVId in (select Eflovid 
                         from EFFieldLOVStaticValue  
                         where efLovId = 49)

在上面的查询中,我想从EFFieldLOVStaticValue表中获取2列并显示。

提前致谢

2 个答案:

答案 0 :(得分:0)

使用join

select R.*, sv.?, sv.?
from EFLOVRelationship R join
     EFFieldLOVStaticValue sv
     ON sv.Eflovid = R.childEFLOVId and sv.efLovId = 49
where R.parentEFLOVValueId = '5320' 

答案 1 :(得分:0)

使用Inner Join

SELECT R.*, 
       V.field1, 
       V.field2 
FROM   eflovrelationship R 
       INNER JOIN effieldlovstaticvalue V 
               ON R.childeflovid = V.eflovid 
WHERE  R.parenteflovvalueid = '5320' 
       AND V.eflovid = 49 

如果您的表格有1:N关系,请使用Distinct以避免重复结果

如果您只希望每个effieldlovstaticvalue列的R.childeflovid表中有一条记录,请使用Cross Apply,但您需要使用必填列来排序结果并选择前1条记录

SELECT R.*, 
       CS.field1, 
       CS.field2 
FROM   eflovrelationship R 
       CROSS apply (SELECT TOP 1 field1, 
                                 field2 
                    FROM   effieldlovstaticvalue V 
                    WHERE  R.childeflovid = V.eflovid 
                           AND eflovid = 49 
                    ORDER  BY someordercolumn) CS 
WHERE  R.parenteflovvalueid = '5320'