简体   繁体   中英

Why does calling MAX on a subquery fail in SELECT?

Can anyone help me answer why my query returns a syntax error? I'm working on the Hackerrank problem linked here .

Here's the code I wrote:

SELECT MAX(SELECT e1.salary * e1.months FROM Employee as e1) as max_tot_earnings, COUNT(e.employee_id)
FROM Employee as e
WHERE e.salary * e.months = max_tot_earnings

I get the following syntax error:

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT e1.salary * e1.months FROM Employee as e1) as max_tot_earnings, COUNT(ee' at line 1

I know that the subquery doesn't have a syntax error. It runs just fine when run on its own. I was also able to work around the problem, so the purpose of this question is to try and figure out what's going on. I was able to solve the problem with the query shown below:

SELECT (SELECT e1.salary * e1.months as tot_earnings FROM Employee as e1 ORDER BY tot_earnings DESC LIMIT 1) as max_tot_earnings, COUNT(e.employee_id)
FROM Employee as e
GROUP BY e.salary, e.months
HAVING e.salary * e.months = max_tot_earnings

I found a few questions here that touch on using SELECT MAX(SELECT ...), but I didn't find answers for the two questions as phrased above. Questions one , two , and three .

In sum, I have two main questions:

  1. Why does the SELECT MAX(SELECT ...) approach return a syntax error? I've used MAX(SELECT ...) statements in HAVING before, so I'm puzzled. Are aggregate functions with subqueries just not allowed in SELECT?
  2. In my search online for an answer to #1, I have seen suggestions move the subquery in the FROM statement. Is this preferable to having the subquery in my SELECT statement (as in my eventual solution shown above)?

The correct syntax is:

SELECT (SELECT MAX(e1.salary * e1.months) FROM Employee as e1) as max_tot_earnings,
       COUNT(e.employee_id)
FROM Employee as e
WHERE e.salary * e.months = max_tot_earnings;

Or more simply as:

SELECT (e.salary * e.months) as max_tot_earnings, COUNT(*)
FROM Employee
GROUP BY max_tot_earnings
ORDER BY max_tot_earnings DESC
LIMIT 1;

Your query doesn't work for the following reasons:

  1. A subquery needs its own set of parentheses. So does a function call. So MAX( (SELECT . . . ) ) at least meets the parentheses requirements.
  2. The MAX() function takes an argument that is either a column reference or a constant or an expression that evaluates to a scalar. Your function call does not do that.
  3. MAX() doesn't allow subqueries at all, even scalar subqueries.

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.

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