2017-06-05 41 views
-1

我對sql相當陌生,並且想要詢問您對此查詢的幫助。有沒有另一種方法來重寫這個?查詢微調

Select * 
From emp 
Where emp_no IN (
    Select emp_no 
    From dept_emp 
    Where dept_no = 'd002' 
    ); 

任何幫助,非常感謝。

謝謝。

回答

1

您可以使用exists

select * 
from emp 
where exists(
    select 1 from dept_emp where dept_emp.emp_no = emp.emp_no and dept_no = 'd002' 
) 

也說不定inner join工作:

select emp.* 
from emp 
join dept_emp 
on dept_emp.emp_no = emp.emp_no 
and dept_no = 'd002' 
+0

爲什麼'不exists'? – harshavmb

+0

@harshavmb我錯了,把'_no'當成'not'。 :-( – Blank

+0

沒有probs。我必須仔細檢查我的答案,因爲你..:p – harshavmb

0

您可以使用內部聯接

select * 
from emp 
inner join (
    Select emp_no 
    From dept_emp 
    Where dept_no = 'd002' 

) t on emp_no.id = t.emp_no 

或無子查詢

select * 
from emp 
inner join dept_emp on emp_no.id = dept_emp.emp_no 
    and dept_emp.dept_no = 'd002' 
0

您可以使用加入這樣的:

select * from emp e, dept_emp d where e.emp_no = d.emp_no and d.dept_no = 'd002'

0
 
- If have the relation between two tables best-way you can used join. other wise you can used inner query (sub select) 
- When you used join in RDBMS it will faster that inner query. 
- join must be indexed based like: primary key and foreign key. Other wise executing cost will be high. non-index query time consumed maximum.