子查询和INTERSECT

时间:2013-10-29 22:43:38

标签: sql oracle intersection

我正在尝试选择教导学生的教师的姓名,邮编和电话号码,这些教师与教练一样生活在同一个邮政编码中

首先我选择zip,其中学生和教师具有相同的ZIP

SELECT ZIP 
FROM STUDENT
INTERSECT
SELECT ZIP
FROM INSTRUCTOR;

它给了我想要的东西

ZIP 
-----
10025

那么我现在如何从已选择的ZIP中选择名字,姓氏和电话?我怎么能把它们结合起来?

SELECT FIRST_NAME,LAST_NAME,PHONE
FROM INSTRUCTOR w, STUDENT s
WHERE w.STUDENT_ID = w.STUDENT_ID
GROUP BY FIRST_NAME,LAST_NAME,PHONE
HAVING COUNT(*) =
(SELECT ZIP
FROM
(SELECT ZIP 
FROM STUDENT
INTERSECT
SELECT ZIP
FROM INSTRUCTOR));

2 个答案:

答案 0 :(得分:1)

您想选择讲师详细信息和学生详细信息吗?如果是这样,试试

SELECT FIRST_NAME,LAST_NAME,PHONE 
FROM
    (
    SELECT FIRST_NAME,LAST_NAME,PHONE,ZIP
    FROM INSTRUCTOR
    UNION ALL
    SELECT  FIRST_NAME,LAST_NAME,PHONE ,ZIP
    FROM STUDENT
    ) 
Derived
 WHERE ZIP IN (SELECT ZIP FROM STUDENT 
               INTERSECT
               SELECT ZIP
               FROM INSTRUCTOR)

更新:如果您只需要教师,那么简单的连接就足够了

SELECT FIRST_NAME,LAST_NAME,PHONE,ZIP
FROM INSTRUCTOR INNER JOIN STUDENT ON INSTRUCTOR.ZIP = STUDENT.ZIP

答案 1 :(得分:0)

我建议加入zip字段中的两个表格。