简体   繁体   English

如何从 Oracle 数据库中获取 MAX

[英]How to get MAX from Oracle database

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.我正在尝试从数据库中获取MAX ,但我正在尝试两种方法,如果两种方法都正确,则需要清除。

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 Q.) 找出控制预算最大的项目的经理的名字

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.你需要join In the most recent versions of Oracle, a simple method uses order by and fetch :在最新版本的 Oracle 中,一个简单的方法使用order byfetch

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.关键是你需要使用正确的、明确的、标准的JOIN语法。

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. select 子句的语法不正确。 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:如果您不想使用 MAX 或将输出限制为一行:

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.这将在proj搜索更高的budet直到没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM