我只想根据 mysql 表中的用户 ID 列选择唯一的行。因此,如果我有两行具有相同的用户 ID,则没有一个会被选中,但如果只有一个会被选中。
我使用以下代码:
SELECT T.id,T.name,T.userid FROM tbltest T WHERE userid NOT IN (SELECT userid FROM tbltest WHERE tbltest.id<>T.id);
这是最快的方法吗?
谢谢!
这怎么样
SELECT T.id,T.name,T.userid
FROM tbltest T
GROUP BY T.userid
HAVING COUNT(T.userid) = 1;
尝试这个:
SELECT T.id, T.name, T.userid, count(*) AS count FROM tbltest GROUP BY T.userid HAVING count = 1;
我认为这不是最快的方法......你可以尝试:
SELECT T.id, T.name, T.userid, COUNT(*) AS num
FROM tbltest T GROUP BY T.userid HAVING num = 1
或者
SELECT T.id, T.name, T.userid, COUNT(*) AS num FROM tbltest T
WHERE NOT EXISTS
(SELECT 1 FROM tbltest T2 WHERE T2.userid = T.userid AND T2.id != T.id)