SQL查询以查找从中选择记录的同一表

时间:2019-03-05 11:59:55

标签: sql oracle performance

样本记录:

Custid pref_location
C1     PUNE
C1     MUMBAI
c1     DELHI    
C2     PUNE
C2     MUMBAI
C3     MUMBAI  
c4     PUNE
C5     DELHI

我想获取首选位置仅是PUNE或MUMBAI的记录。我在以下查询的帮助下进行操作:

SELECT *
FROM EMP_PRE_LOCATION E1
WHERE EXISTS (SELECT 1 
        FROM EMP_PRE_LOCATION E2 
        WHERE E2.EID=E1.EID AND E2.PRE_LOCATION in ('PUNE','MUMBAI'))
AND NOT  EXISTS (SELECT 1 
        FROM EMP_PRE_LOCATION E3 
        WHERE E3.EID=E1.EID AND E3.PRE_LOCATION NOT in('PUNE','MUMBAI'));

实现相同目标是他们更好的方法吗?

3 个答案:

答案 0 :(得分:1)

我想你只是想要

SELECT E1.*
FROM EMP_PRE_LOCATION E1
WHERE NOT EXISTS (SELECT 1 
                  FROM EMP_PRE_LOCATION E2 
                  WHERE E2.EID = E1.EID AND
                        E2.PRE_LOCATION NOT IN ('PUNE', 'MUMBAI')
                 );

如果您只希望在这两个位置工作,则可以使用GROUP BYHAVING

SELECT E1.EID
FROM EMP_PRE_LOCATION E1
GROUP BY E1.EID
HAVING SUM(CASE WHEN E1.PRE_LOCATION NOT IN ('PUNE', 'MUMBAI') THEN 1 ELSE 0 END) = 0;

如果需要位置列表,可以添加LISTAGG(E1.PRE_LOCATION, ',')

答案 1 :(得分:1)

请尝试这个。

SELECT *
FROM EMP_PRE_LOCATION
WHERE pref_location ='PUNE' OR pref_location ='MUMBAI'

答案 2 :(得分:0)

第二个WHERE子句可以满足您的需求:

SELECT E1.*
FROM EMP_PRE_LOCATION E1
WHERE E1.PRE_LOCATION IN ('PUNE','MUMBAI') AND 
      NOT EXISTS (SELECT 1 
                  FROM EMP_PRE_LOCATION E3 
                  WHERE E3.EID = E1.EID AND E3.PRE_LOCATION NOT IN ('PUNE','MUMBAI')
                 );

这将仅返回只有EID的{​​{1}}个。