简体   繁体   中英

MySQL - select highest salary

i need to select a person who lives in a city which name starts with "W" letter and has the highest salary. I tried this condition:

SELECT o.imię, o.nazwisko, e.pensja, mO.nazwa 
    FROM etaty e, osoby o, miasta mO
    WHERE(e.id_osoby = o.id_osoby) AND (mO.id_miasta = o.id_miasta) 
    AND mO.nazwa LIKE 'W%' 
    AND  e.pensja = (SELECT MAX(eW.pensja) AS mp FROM etaty eW)
/* pensja = salary */

I have no errors but no results. When i try to drop out this salary condition everything work perfectly fine or when i try to drop out this name condition - also. But i can't mix this two conditions and make it work fine. What should i do?

Using LIMIT might be the easiest option here:

SELECT o.imię, o.nazwisko, e.pensja, mO.nazwa 
FROM etaty e
INNER JOIN osoby o ON e.id_osoby = o.id_osoby
INNER JOIN miasta mO ON mO.id_miasta = o.id_miasta
WHERE mO.nazwa LIKE 'W%'
ORDER BY e.pensja DESC
LIMIT 1;

One possible reason your current query is failing is that your max subquery is finding the highest salary of a point in your data set which is being filtered out by the joins. To remedy this, you could just include the full join structure in the max subquery:

SELECT o.imię, o.nazwisko, e.pensja, mO.nazwa 
FROM etaty e
INNER JOIN osoby o ON e.id_osoby = o.id_osoby
INNER JOIN miasta mO ON mO.id_miasta = o.id_miasta
WHERE
    mO.nazwa LIKE 'W%' AND
    e.pensja = (SELECT MAX(ew.pensja)
                FROM etaty ew
                INNER JOIN osoby ow ON ew.id_osoby = ow.id_osoby
                INNER JOIN miasta mOw ON mOw.id_miasta = ow.id_miasta
                WHERE mOw.nazwa LIKE 'W%');

It is hard to say anything without tables their data but one suspicious this is table "etaty" is not connected properly with the other 2 tables so

SELECT MAX(eW.pensja) AS mp FROM etaty eW

does not correspond with with:

AND mO.nazwa LIKE 'W%' 

it might be that there is no person starting with W having the highest salaries I think you need to add the same condition the select max(pensja) sub-query.

However I might be wrong as it's hard to predict without structure.

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