I am trying to get the MAX
from a database but I am trying two methods, and need to be cleared if both methods are correct or not.
These are my Object types:
Emp_t (eno: number(4), ename: varchar2(15), edept: ref dept_t, salary: number(8,2))
Dept_t (dno: number(2), dname: varchar2(12), mgr ref emp_t)
Proj_t (pno: number(4), pname: varchar2(15), pdept ref dept_t, budget: number(10,2))
And these are my Tables:
Emp of Emp_t (eno primary key, edept references dept)
Dept of Dept_t (dno primary key, mgr references emp)
Proj of Proj_t (pno primary key, pdept references dept)
My question is:
Q.) Find the manager's name who is controlling the project with the largest budget
My first answer is:
SELECT p.pdept.mgr.ename
FROM proj p
WHERE p.budget IN (SELECT MAX(p.budget) FROM proj p)
And my second answer is:
SELECT p.pdept.mgr.ename, MAX(p.budget)
FROM proj p
I need to know which answer is correct. or both are right. If one is incorrect the reason for that?
You need join
s. In the most recent versions of Oracle, a simple method uses order by
and fetch
:
select e.name
from proj_t p join
emp_t e
on p.mgr = e.eno join
dept_t d
on p.pdept = d.dno
order by p.budget desc
fetch first 1 row only;
The key point is that you need to use proper, explicit, standard JOIN
syntax.
Neither of your queries are right.
Issue with 1st Query -
SELECT p.pdept.mgr.ename ----- This is not the correct syntax
FROM proj p
WHERE p.budget IN (SELECT MAX(p.budget) FROM proj p)
The syntax is not correct for select clause. The syntax should be -
SELECT e.name
FROM proj_t p
INNER JOIN emp_t e ON p.mgr = e.eno
INNER JOIN dept_t d ON p.pdept = d.dno
WHERE p.budget = (SELECT MAX(budget) FROM proj_t);
Issue with 2nd Query -
SELECT p.pdept.mgr.ename, MAX(p.budget) ----- You cannot use other columns with aggregate function without group by clause.
FROM proj p
Please use the above query and you will get your desired result.
If you don't want to use MAX or limit the output by one row:
SELECT p.pdept.mgr.ename
FROM proj p
WHERE NOT EXISTS(
SELECT *
FROM proj subp
WHERE subp.budget > p.budget
)
This will search for a higher budet
in proj
untill there is none.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.