1

I have a table like this:

column_a  column_b
  foo        1
  bar        1
  bar        2
  baz        4

I'd like to have following result, containig all rows, that have a unique field value in column_b:

  bar        2
  baz        4

foo(0) and bar(1) both have the column_b value '1', so the '1' is not unique. Is there a MySQL-Expression that filters all rows that have a unique column_b?

Maybe something like that:

select * from table where isunique(column_b)

In Addition: I do not need something like DISTINCT!

edit (solved):

Thanks to YaK and jcho360, this one is the solution:

select column_a, column_b from table group by column_b having count(column_b) = 1

OR

select column_a, column_b, COUNT(1) AS total from table group by column_b having total = 1

(thx to andrewtweber)

4
  • 1
    These answers help you? mark one as correct Commented Jun 13, 2012 at 17:54
  • 1
    @Nikolai Wüstemann: No problem, but I wouldn't mind a +1 instead ;) Commented Jun 13, 2012 at 18:21
  • Oh my bad, I think you need more reputation to do that. Commented Jun 13, 2012 at 19:59
  • No I have enough and I did my job! ;) Thank you! Commented Jun 13, 2012 at 23:33

3 Answers 3

4

Using the count function will provide a selection where the value in column_b only occurs once. Try this:

select * from table group by (column_b) having count(column_b) = 1;
Sign up to request clarification or add additional context in comments.

1 Comment

HAVING COUNT(column_b) = 1 should suffice, because if there is no row, then it is not included in the result at all. Even worse if your column_b contains NULL values: then their COUNT() equals 0, and will be returned (with a "random" value as column_a value)
3
SELECT column_a, column_b, COUNT(1) AS total
FROM table
GROUP BY column_b
HAVING total = 1

I believe that should work. This groups all column_b together and counts how many have that particular value, then limits the result set to those with a unique column_b value.

Comments

-1

Try select unique(column_b), column_a, from table instead? :)

Edit fix typo

2 Comments

-1: in which version did they introduce the UNIQUE() function?
Whoops my bad, was thinking Oracle syntax where unique works as distinct :(

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.