0

So I've made a simple SQL query:

SELECT companyname
FROM works w1, (
                SELECT companyname,sum(salary) AS sumsal
                FROM works
                GROUP BY companyname
               ) w2
WHERE
w1.companyname=w2.companyname

it works fine so far but then I add the following line in the where clause:

AND w2.sumsal=(SELECT MIN(w2.sumsal)
               FROM w2);

I get:

ERROR 1146 (42S02): Table 'companydb.w2' doesn't exist

I'm using MySQL 8.0.

  • 1
    What exactly do you want the query to show? The company that pays the lowest sum of salaries? – ypercubeᵀᴹ Oct 28 '18 at 17:11
1

Before answering the question, you are using WHERE instead of JOIN for joining the tables, and join the tables using the company name instead of the row ID / primary key. It's better use JOIN with row ID when joining tables (if your are using the company name as the primary key you really have to add to add a row ID and use it instead as the key).

Regarding your question, the problem is that the subquery w2 can't be used in the right part of the SELECT because is out of scope, but you can use a Common Table Expression to create a "temporary view" that can be used in any part of the query. Then you can use two methods for getting the result:

Using MIN():

with sums as (select companyname, sum(salary) AS sumsal
  from works
  group by companyname
)
select *
from sums
where sumsal=(select min(sumsal) from sums)

Using EXISTS:

with sums as (select companyname, sum(salary) AS sumsal
  from works
  group by companyname
)
select *
from sums
where not exists (select * from sums s2 where s2.sumsal<sums.sumsal)

I have created this db<>fiddle for testing it online, there I have used JOIN with the company Id instead of the name as an example of how you can use that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.