Only returning rows when there is a certain count of a given column
I'm trying to make a SELECT
query which only returns 开发者_如何学JAVArows when a column (call it My_Column
) has only one distinct value, that is when COUNT(DISTINCT My_Column) = 1
. If there are multiple distinct values of My_Column
, I don't want any rows returned. How can I do that?
Use:
SELECT t.*
FROM YOUR_TABLE t
HAVING COUNT(DISTINCT t.my_column) = 1
Be aware of how MySQL handles GROUP BY and HAVING with Hidden Columns.
SELECT ...
GROUP BY foo
HAVING COUNT(DISTINCT My_Column) = 1;
SELECT a.*
FROM table a
WHERE 1 = (SELECT COUNT(DISTINCT My_Column) FROM table);
Try this:
SELECT COUNT(My_Column), My_Column FROM tbl GROUP BY My_Column HAVING COUNT(My_Column)=1
精彩评论