3

Is there a way in mysql to check one specific column and see if the value occurs more then one time, and if so get the row.

lets say that my table looks like this:

id | first_name | last_name | age
1     john           doe       20
..    .......       .....     ...
..    .......       .....     ...

So I want the mysql to go and bring back a list where the age is 18 AND where the first_name occurs more then once.

2
  • 1
    Is performance an issue? Commented Oct 3, 2011 at 19:58
  • possible duplicate of Find duplicate records in MySQL Commented Oct 4, 2011 at 9:33

3 Answers 3

5
SELECT y.id, y.first_name, y.last_name, y.age
    FROM (SELECT first_name
              FROM YourTable
              WHERE age = 18
              GROUP BY first_name
              HAVING COUNT(*) > 1) t
        INNER JOIN YourTable y
            ON t.first_name = y.first_name
    WHERE y.age = 18;
Sign up to request clarification or add additional context in comments.

Comments

2

You can use a JOIN:

SELECT DISTINCT T1.first_name
FROM yourtable T1
JOIN yourtable T2
ON T1.id < T2.id
AND T1.first_name = T2.first_name
AND T2.age = 18
WHERE T1.age = 18

5 Comments

@Joe Stefanelli: Thanks, added.
You added it so fast, I deleted my original comment thinking I had misread your answer the first time! :-)
Great answer! I dint think that it is possible in MySQL without HAVING! Ill use it my heave load project! If it possible, I`ll set you more than one +1 vote!
@Joe Stefanelli: Well actually I had already added the fix just before you commented, but I'm grateful for you pointing it out anyway. :)
This is only returning one of the "dublicates" and not all of them, other then that great answer!
0
select id, first_name, last_name, age
from YourTable where first_name in
(
    select first_name
    from YourTable 
    where age = 18
    group by first_name
    having count(first_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.