Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correlated query: select where condition not max(condition in inner query)

I am trying to select all the rows where the userName and groupId is duplicated, and the userId is not the max userId for that userName/groupId combination. Here is my code so far:

select *
from userTable u
where exists
    (select *
    from userTable u1
    where userName <> '' and userName is not null
    and u.userName = u1.userName and u.groupId = u1.groupId
    and u.userId <> max(u1.userId)
    group by userName, groupId
    having count(*) > 1)
order by userName

However, the line:

and u.userId <> u1.max(userId)

is giving me an error.

What is the right way to do this query?

like image 344
dmr Avatar asked Jan 18 '26 20:01

dmr


1 Answers

SELECT  u.*
FROM    (
        SELECT  userName, groupId, MAX(userId) AS maxId
        FROM    userTable
        GROUP BY
                userName, groupId
        HAVING  COUNT(*) > 1
        ) q
JOIN    userTable u
ON      u.userName = q.userName
        AND u.groupId = q.groupId
        AND u.userId <> q.maxId
like image 55
Quassnoi Avatar answered Jan 21 '26 11:01

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!