One field identical, one field different (MySQL)

Trustyphone Pueblo :

So I'm looking at a table like this:

    TABLE NAME: DD
    --------------------------------------
    ID   | EMPLOYEE_ID  |       NAME     |   
    --------------------------------------
    1    |    100       | ABLE           |
    2    |    100       | ABLE           |
    3    |    101       | BAKER          |
    4    |    101       | CHARLIE        |
    5    |    102       | DOG            |
    6    |    102       | EASY           |
    7    |    102       | DOG            |
    --------------------------------------

There are thousands of records, every EMPLOYEE_ID is in there at least twice. I am looking for a query that will return all the records where the EMPLOYEE_ID is identical but the NAME is not. So like this:

    --------------------------------------
    ID   | EMPLOYEE_ID  |       NAME     |   
    --------------------------------------
    3    |    101       | BAKER          |
    4    |    101       | CHARLIE        |
    5    |    102       | DOG            |
    6    |    102       | EASY           |
    --------------------------------------

I've tried this, which should work in theory, but it causes an error due to the temp order running out of space:

SELECT A.* 
FROM DD A
INNER JOIN DD B
 on A.EMPLOYEE_ID = B.EMPLOYEE_ID
 and A.NAME <> B.NAME
ORDER BY A.EMPLOYEE_ID
VBoka :

This will give you the exact result you asked:

select min(id) ID
       , EMPLOYEE_ID
       , NAME
from DD
where EMPLOYEE_ID in ( select e_id 
                       from (SELECT name
                                    , count(EMPLOYEE_ID)
                                    , max(EMPLOYEE_ID) e_id
                             FROM DD 
                             group by name) a
                       group by e_id
                       having count(e_id) > 1 )
group by EMPLOYEE_ID
         , NAME;

Here is a demo

The forpas is correct when he say: "This code is wrong. Check this: dbfiddle.uk/… ". Here is another code:

select min(id) ID
       , EMPLOYEE_ID
       , NAME
from DD
where EMPLOYEE_ID in ( SELECT distinct EMPLOYEE_ID e_id
                       FROM DD 
                       group by EMPLOYEE_ID
                       having count(distinct name) > 1 )
group by EMPLOYEE_ID
         , NAME;

Here is a demo

Result:

enter image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=10166&siteId=1