我正在使用oracle,下面我有一个基本的SQL查询,我选择了一个团队使用join
的学校。然而,我正在努力如何使用连接选择相反的(没有团队的学校)。我尝试使用outter
,inner
,left
和right
这两个词,但无济于事,我得到了我想要的结果。如何列出没有团队的学校?
查询:
SELECT DISTINCT a.school_name, a.school_id, b.school_id FROM School a RIGHT OUTER JOIN Team b ON a.school_id = b.school_id;
结果:
SCHOOL_NAME SCHOOL_ID SCHOOL_ID
------------------------- ---------- ----------
Panthers University 92022 92022
Blue Rays Middle School 22149 22149
表:
schools
SCHOOL_ID SCHOOL_NAME SCHOOL_TYPE
---------- ----------------------------- ------------
92022 Panthers University University
22149 Blue Rays Middle School Middle SchooL
21719 Bull Dogs High School High SchooL
42736 Saint Lucia Grade School Middle SchooL
school_teams
TEAM_ID SPORT_ID SCHOOL_ID TEAM_NAME
---------- ---------- ---------- ----------
1 1 92022 Panthers
2 1 22149 Blue Rays
答案 0 :(得分:2)
使用Not exists
执行此操作。
SELECT a.school_name, a.school_id
FROM School a
where not exists (select 1 from Team b where a.school_id = b.school_id)
答案 1 :(得分:1)
所有这些连接(内部,外部,左侧,右侧)仅选择匹配的行。您正在寻找不匹配的行,因此它们不适合您。
试试这个:
SELECT DISTINCT school_id, school_name FROM school
WHERE school_id not in
(SELECT school_id FROM school_teams)
答案 2 :(得分:0)
尝试:
SELECT DISTINCT a.school_name, a.school_id, b.school_id FROM School a LEFT OUTER JOIN Team b ON a.school_id = b.school_id;
答案 3 :(得分:0)
编写此查询以生成所需的结果集。使用左加入。
SELECT Table1.School_Name, Table1.School_Id FROM Table1 LEFT JOIN Table2 ON Table1.School_Id = Table2.School_Id where Table1.School_Id NOT IN (Select DISTINCT Table2.School_Id From Table2);