如何使用sql显示唯一记录号?

时间:2016-11-19 10:38:11

标签: mysql

我有学生表

id | name | zip 
1  | abc  | 1234
2  | xyz  | 4321
3  | cde  | 1234

我想只显示4321的唯一邮政编码。我不想显示1和3的记录编号。那么,我怎样才能显示唯一的记录呢?

提前致谢。

3 个答案:

答案 0 :(得分:4)

以下查询将为您提供所有未重复出现的邮政编码:

SELECT zip
FROM yourTable
GROUP BY zip
HAVING COUNT(*) = 1

如果你想获取完整记录,那么你可以使用上面的子查询来过滤原始表:

SELECT *
FROM yourTable t1
INNER JOIN
(
    SELECT zip
    FROM yourTable
    GROUP BY zip
    HAVING COUNT(*) = 1
) t2
    ON t1.zip = t2.zip

或者这个:

SELECT *
FROM yourTable
WHERE zip IN
(
    SELECT zip
    FROM yourTable
    GROUP BY zip
    HAVING COUNT(*) = 1
)

答案 1 :(得分:1)

这也可行

select 
    id, name, zip
from
    (select 
        id, name, zip, count(zip) as countZip
    from
        student
    group by zip) as subq
where
    countZip = '1'

答案 2 :(得分:0)

DISTINCT修饰符强制select只显示可能多次出现的列的一个值。在你的情况下,它将是:

SELECT DISTINCT ZIP
  FROM ...