简体   繁体   中英

mysql select unique row

I have the following table - mytable :

----id----|----user_id----|----value-----|
----1-------------1------------- 9
----2-------------1------------- 8
----3-------------2 -------------11
----4-------------2-------------12
----5-------------3-------------11
----6-------------4-------------8
----7-------------1-------------3

I want to SELECT * FROM mytable... where value has a single record like this:

----id----|----user_id----|----value-----
----1-------------1-------------9
----4-------------2-------------12
----7-------------1-------------3

Note that value 8 and value 11 have duplicates and I removed all

Try this

SELECT * FROM mytable
GROUP BY `value`
HAVING count(*) = 1

or

SELECT * FROM mytable
GROUP BY `value`
HAVING count(*) < 2

You could try a left join:

SELECT T1.id, T1.user_id, T1.value
FROM yourtable T1
LEFT JOIN yourtable T2
ON T1.value = T2.value
AND T1.id <> T2.id
WHERE T2.id IS NULL

The below query should work fine for the question asked above..

SELECT T1.* FROM MYTABLE T1, ( SELECT VALUE FROM MYTABLE GROUP BY VALUE HAVING COUNT(*)=1 ) T2 WHERE T1.VALUE = T2.VALUE;

Regards, Venk

I would do this:

select t1.* 
from table1 t1
where 1 = (select count(t2.id)
                    from table1 t2
                    where t1.value = t2.value 
                    )

Hope it works.

PS: id has to be the unique key.

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