简体   繁体   中英

Remove all query results that have duplicates (NOT DISTINCT)

I have a table with two sets of integer values. Using MySQL I want to display all of the rows that correspond to unique entries in the second column. Basically I can have duplicate A values, but only unique B values. If there are duplicates for a value in B, remove all the results with that value. If I use DISTINCT I will still get one of those duplicates which I do not want. I also want to avoid using COUNT() . Here's an example:

|_A____B_|
| 1    2 |
| 1    3 |
| 2    2 |
| 2    4 |
| 1    4 |
| 5    5 |

Will have the following Results (1,3), (5,5). Any value in B that has a duplicate is removed.

Try this

SELECT * FROM TEMP WHERE B IN (
  SELECT B FROM TEMP GROUP BY B Having COUNT(B)=1
 );

I know you want to avoid using COUNT() but this is the quick solution.

working fiddle here - http://sqlfiddle.com/#!9/29d16/8

Tested and works! you need atleast count(*) to count the values

 select * from test where B in (
   select B from test  group by B  having count(*)<2
 )

I don't know why you want to avoid using count(), because that's what would do the trick as follows:

Let's say your table is named "mytable"

SELECT t1.A, t1.B
FROM mytable t1
JOIN (
    SELECT B, count(*) AS B_INSTANCES
    FROM mytable
    GROUP BY B
    HAVING count(*) = 1
) t2 ON t2.B = t1.B
ORDER BY t1.A, t1.B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM