SQL查询不同的问题

时间:2015-06-16 10:45:16

标签: c# sql sql-server sql-server-2008

我写了下面的查询来列出表[HRSurvey]中的所有行 empid仅出现在empsurveyselection中。两个表都有empid列。

但是因为那里我无法得到正确的结果 在empsurveyselection表中可能是同一个surveyid的多重empid。 但是,当empsurveyselection表中的每个surveyid只有一个empid时,此查询可以正常工作。

请问您是否可以重写查询以列出表格HRSurvey中emps在选举中所有行的所有行?

SELECT  hrs.* 
  FROM [HRSurvey] hrs
Left Join [HRSurveyEmployee] hse
ON hse.EmpID =  hrs.EmpID 
LEFT Join Surveys s 
ON s.surveyid = hse.surveyid 
WHERE hrs.empid IN (
SELECT empid FROM [HRSurveyEmployee] where surveyid = s.surveyid 
) and sempid 
in ( select DISTINCT empid FROM empsurveyselection WHERE deptid=9 and surveyid = s.surveyid) 

3 个答案:

答案 0 :(得分:3)

你可以写成:

SELECT hrs.col1, -- Worst Practice to use * in production code to pull data
       hrs.col12 -- Use explicit column names instead
FROM [HRSurvey] hrs
INNER JOIN [HRSurveyEmployee] hse ON hse.EmpID =  hrs.EmpID 
INNER JOIN [Surveys] s ON s.surveyid = hse.surveyid 
INNER JOIN [empsurveyselection]ess ON ess.deptid=9 
AND ess.surveyid = s.surveyid AND hrs.sempid = ess.empid

答案 1 :(得分:1)

请尝试使用以下查询....

select  a.*
from    HRSurvey a
where   empid exists (select  1
                      from    empsurveyselection b
                      where   a.Empid = b.Empid)

答案 2 :(得分:0)

感谢您的帮助!实际上问题不在于查询。问题与数据有关,我修复了它。