我需要帮助优化这个SQL查询。
我有一个名为Student
的表,其中包含以下列:
id; Department_Name; Parent_Department
值例如:
id Department_Name Parent_Department
1 IT_CS
2 IT_BP
3 IT_NP
4 IT1 1
5 IT2 1
6 IT3 3
7 IT4
8 IT9 2
我的需要是从表中获取所有id,其中parent_department = IT_CS; 为此我写了2个查询
select id from student where Department_Name ='IT_CS';
select id from student where parent Parent_Department =Id
;
有没有更好的方法呢?
答案 0 :(得分:0)
您可以像这样使用
select id,Department_Name,Parent_Department
from student as a
inner join student as b on a.parent_Department= b.id
where b.Department_Name='IT_CS'
答案 1 :(得分:0)
SELF Join语句专门用于此目的,
SELECT *
FROM STUDENT S
JOIN STUDENT S1 ON S.PARENT_DEPARTMENT = S1.ID
WHERE S1.DEPARTMENT_NAME = 'IT_CS'