1

我正在学习 MySQL,我正在尝试在查询中进行简单的算术运算,我正在尝试识别平均工资最高的部门并获取部门名称。但我不知道如何 ProfessorsTable使用外键访问表。任何人都可以帮助我吗?谢谢!

这是我试过的:

 SELECT Department FROM ProfessorsTable WHERE max(AVG(Salary));

下面是我的两张表:

 CREATE TABLE DepartmentsTable
 (
   Department VARCHAR(50) NOT NULL,
   Faculty VARCHAR(50) NOT NULL,
   Building VARCHAR(50) NOT NULL,
   CONSTRAINT PRIMARY KEY (Department)
 ) type = InnoDB;

 CREATE TABLE ProfessorsTable
 (
   Name VARCHAR(50) NOT NULL,
   Department VARCHAR(50) NOT NULL,
   Rank VARCHAR(50) NOT NULL,
   Salary INT UNSIGNED NOT NULL,
   CONSTRAINT FOREIGN KEY (Department) REFERENCES DepartmentsTable(Department), 
   CONSTRAINT PRIMARY KEY (Name, Department)
 ) type = innoDB;
4

2 回答 2

2

得到所有部门的平均工资。. .

SELECT Department, avg(Salary) AS avg_salary
FROM ProfessorsTable 
GROUP BY Department
ORDER BY avg_salary DESC;

只取平均分最高的部门。. .

SELECT Department, avg(Salary) AS avg_salary
FROM ProfessorsTable 
GROUP BY Department
ORDER BY avg_salary DESC LIMIT 1;
于 2013-05-12T00:17:22.287 回答
1

为了做你想做的事,工作流程如下:

您想选择薪水最高的教授的部门名称。因此,您想按薪水对教授进行排序,选择列表中的第一个(最高薪水),然后返回他/她的部门。

试试这个:

SELECT Department FROM ProfessorsTable ORDER BY Salary DESC LIMIT 1;

编辑:

我误读了原来的问题。下面是获取工资最高部门的部门名称的方法:

SELECT Department FROM ProfessorsTable GROUP BY Department ORDER BY AVG(salary) DESC LIMIT 1;

基本思想是 sam:您首先按平均工资排序,然后选择只保留第一个结果。

于 2013-05-11T23:36:59.370 回答