如何在另一个表中选择具有特定值/条件的记录

时间:2017-12-08 15:47:55

标签: sql oracle

我有3张桌子学生,主题和等级。

STUDENT

+------------+------------+------------+
| student_id | first_name |  last_name |
+------------+------------+------------+
|          0 | Arthur     | Pain       |
|          1 | Richard    | Gordon     |
|          2 | Jennifer   | Adelaide   |
+------------+------------+------------+

SUBJECT

+------------+--------------+
| subject_id | subject_name |
+------------+--------------+
|        001 | Math         |
|        002 | Science      |
|        003 | English      |
+------------+--------------+

GRADE

+-------------+-------------+--------+
| student_id  | subject_id  |  grade |  
+-------------+-------------+--------+
| 0           | 001         | A      |  
| 0           | 002         | B      |  
| 0           | 003         | A      |  
| 1           | 001         | B      |  
| 1           | 002         | A      |  
| 1           | 003         | F      |  
| 2           | 001         | A      |  
| 2           | 002         | B      | 
| 2           | 003         | B      |
+-------------+-------------+--------+

我已尝试过以下查询。

SELECT * FROM student st WHERE EXISTS 
       (SELECT 1 FROM grade g WHERE st.student_id = g.student_id AND g.grade IN ('A','B');

我想选择成绩仅为'A'或'B'的学生。

6 个答案:

答案 0 :(得分:0)

如何简单地添加NOT EXISTS:

SELECT *
 FROM student st
 WHERE EXISTS (SELECT NULL
                 FROM grade g 
                WHERE st.student_id = g.student_id
                  AND g.grade IN ('A','B'))
AND NOT EXISTS (SELECT NULL
                  FROM grade g
                WHERE st.student_id = g.student_id
                  AND g.grade IN ('C', 'D', 'F'))

答案 1 :(得分:0)

尝试:

SELECT *
  FROM student s
 WHERE NOT EXISTS
          (SELECT 1
             FROM grade g
            WHERE g.student_id = s.student_id AND grade NOT IN ('A', 'B'));

答案 2 :(得分:0)

您可以使用连接来连接多个表

select s.*,g.* from student as s
inner join GRADE as g on g.student_id=s.student_id
inner join SUBJECT as sj on sj.subject_id = g.subject_id
where g.grade in ('A','B')

我希望这会有所帮助

答案 3 :(得分:0)

SELECT * FROM STUDENT 
LEFT JOIN GRADE ON STUDENT.STUDENT_ID = GRADE.STUDENT_ID
LEFT JOIN SUBJECT ON GRADE.SUBJECT_ID = SUBJECT.SUBJECT_ID 
WHERE GRADE.GRADE IN ('A','B')

答案 4 :(得分:0)

使用Not In:

SELECT * FROM student st WHERE student_id not in 
       (SELECT student_id FROM grade g WHERE grade = 'F');

答案 5 :(得分:0)

SELECT *
  FROM STUDENT
 WHERE student_id IN ( SELECT student_id
                         FROM GRADE
                        WHERE grade IN ( 'A', 'B' ) );

可替换地:

SELECT DISTINCT student_id, first_name, last_name
  FROM STUDENT NATURAL JOIN GRADE
 WHERE grade IN ( 'A', 'B' );