您的派生表需要一个名称,这是错误消息所抱怨的名称(见YouNeedToPutATableAliasHere
下文):
SELECT CONCAT(FName,' ',LName) AS Faculty,DepartmentID,Salary
FROM Faculty,
(SELECT DISTINCT DepartmentID AS Department, MIN(Salary) AS MinSalary
FROM Faculty GROUP BY DepartmentID) AS YouNeedToPutATableAliasHere
WHERE Faculty.DepartmentID= 'Department' AND Salary= MinSalary
ORDER BY DepartmentID
请注意,我还删除了一些对我没有意义的单引号。(也许您的意思是双引号、方括号或反引号表示列名,但单引号可能不起作用——您可能需要对“部门”做同样的事情?)
除非您指定关联两个表的条件,否则您还将创建笛卡尔连接。一个更好的查询“部门最低工资的教师'Department'
”可能是(注意我已经删除了多余的 GROUP BY):
SELECT CONCAT(FName,' ',LName) AS Faculty,F.DepartmentID,F.Salary
FROM Faculty F
INNER JOIN (
SELECT DepartmentID,
MIN(Salary) AS MinSalary
FROM Faculty
GROUP BY DepartmentID
) AS MinSal ON MinSal.DepartmentID = F.DepartmentID
AND F.Salary = MinSal.MinSalary
WHERE F.DepartmentID= 'Department'
ORDER BY F.DepartmentID
或者,由于您只选择一个部门'Department'
,您可以这样做:
SELECT CONCAT(FName,' ',LName) AS Faculty,F.DepartmentID,F.Salary
FROM Faculty F
WHERE F.DepartmentID= 'Department'
AND F.Salary = (
SELECT MIN(Salary)
FROM Faculty
WHERE DepartmentID = F.DepartmentID
)
甚至(这也适用于多个部门,但可能比加入慢):
SELECT CONCAT(FName,' ',LName) AS Faculty,F.DepartmentID,F.Salary
FROM Faculty F
WHERE F.DepartmentID= 'Department'
AND NOT EXISTS(
SELECT 1
FROM Faculty FF
WHERE FF.DepartmentID = F.DepartmentID
AND FF.Salary < F.Salary
)
事实上,在查看您的原始查询并在阅读@RichardTheKiwi 的评论时努力使这个问题完整,我会将这种解释纳入这个答案。这假设您正在使用 MySQL(来自 CONCAT 函数)并且您的意思是反引号而不是列名的正向刻度。它还假设您想要每个部门的最低工资教师,而不仅仅是指定的“部门”。不过,它只需要对我的第一个建议查询进行一些小WHERE
改动 - 即删除该子句:
SELECT CONCAT(FName,' ',LName) AS Faculty,F.DepartmentID,F.Salary
FROM Faculty F
INNER JOIN (
SELECT DepartmentID,
MIN(Salary) AS MinSalary
FROM Faculty
GROUP BY DepartmentID
) AS MinSal ON MinSal.DepartmentID = F.DepartmentID
AND F.Salary = MinSal.MinSalary
ORDER BY F.DepartmentID