1

I need to find inside my table on my MySQL database duplicated values with the same name but with different sport. Here is an example of data:

John Smith    Athletics
Edward Green  Athletics
Edward Green  Fencing
Jim Brown     Rugby
Jim Brown     Rowing
Jim Brown     Sailing
Stan Smith    Football
Stan Smith    Football

Well, I'd like to make a query which give me this result:

Edward Green  Athletics
Edward Green  Fencing
Jim Brown     Rugby
Jim Brown     Rowing
Jim Brown     Sailing

As I said, only that values with the same name but different sport, in order to find namesakes.

4 Answers 4

2

Here's one option using exists:

select *
from yourtable t
where exists (
    select 1
    from yourtable t2
    where t.name = t2.name and t.sport != t2.sport
    )
Sign up to request clarification or add additional context in comments.

Comments

1

The inner select gets all names having more than one distinct sport. To also get the sports for those names, you have to join against the same table

select t1.*
from your_table t1
join
(
    select name
    from your_table
    group by name
    having count(distinct sport) > 1
) t2 on t1.name = t2.name

1 Comment

Could you add some explanation?
1
SELECT name
FROM (SELECT DISTINCT name, sport FROM My_table) AS Temporary_table_name
GROUP BY name
HAVING ( COUNT(name) > 1 )

With command

SELECT DISTINCT name, sport

you exclude duplicated combinations of name and sport (namely "Stan Smith - Football") and after it you can look for repeated names with peace of mind (because you know they won't refer to the same sport)

Comments

-1

Another posbility with no suquery will be to use Having with a COUNT :

SELECT * 
FROM yourtable t
GROUP BY name
HAVING ( COUNT(name) > 1 )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.