2017-06-05 54 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.