tags:

views:

51

answers:

4

I want to do something like:

SELECT * 
  FROM db.table 
 WHERE COUNT(someField) > 1

how do I do this in MySql.

+2  A: 

Use the HAVING, not WHERE clause, for aggregate result comparison.

Taking the query at face value:

SELECT * 
  FROM db.table 
HAVING COUNT(someField) > 1

Ideally, there should be a GROUP BY defined for proper valuation in the HAVING clause, but MySQL does allow hidden columns from the GROUP BY...

Is this in preparation for a unique constraint on someField? Looks like it should be...

OMG Ponies
Needs a `GROUP BY` surely (unless this is some MySQL non standard thing)?
Martin Smith
@Martin Smith: Took the query at face value; addressed GROUP BY issue (incl. hidden columns feature).
OMG Ponies
"Looks like it should be..." Why? I am in need of education on this :)
Dave
So this will return the whole table if it contains more than 2 non null `someField` values or an empty result set if it doesn't.
Martin Smith
OMG Ponies
@Martin Smith: I think it's a poor example, and there's no details currently to go on.
OMG Ponies
I understand your original comment now. I thought there was something special about the query that I wasn't getting. Thanks.
Dave
+1  A: 

One way

SELECT t1.* 
FROM db.table t1
WHERE exists 
      (SELECT *
      FROM db.table t2 
      where t1.pk != t2.pk 
      and t1.someField = t2.someField)
Martin Smith
A: 

As OMG Ponies stated, the having clause is what you are after. However, if you were hoping that you would get discrete rows instead of a summary (the "having" creates a summary) - it cannot be done in a single statement. You must use two statements in that case.

Brent Arias
Not entirely true - use the GROUP BY to manipulate what the HAVING is using.
OMG Ponies
+1  A: 

You can also do this with a self-join:

SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk
Bill Karwin