如何在一个字段中找到重复项,而不是另一个字段中的重复项

时间:2019-07-17 15:55:18

标签: mysql sql having

我正在尝试从表格中提取帐号和邮政编码,其中邮政编码是重复的,但帐号不是(仅在存在邮政编码的地方)

例如,名为mailing的表具有以下字段:-

acc....custname.............postcode
B102...BILLYS SHOES.........LE54 2YZ
B104...BILLYS SHOES.........LE54 2YZ
D200...FANSY................RM5 6LW
D200...FANSY(2ND ACCOUNT)...RM5 6LW
T502...WELLIES R US.........
T502...WELLIES R US.........
    ...THE SHOE SHOP........DN54 05Y
X102...THE SHOE SHOP........DN54 05Y

因此,我尝试按计数> 1的邮政编码进行分组,效果很好,并且可以显示

acc....custname.............postcode
B102...BILLYS SHOES.........LE54 2YZ
B104...BILLYS SHOES.........LE54 2YZ
D200...FANSY................RM5 6LW
D200...FANSY(2ND ACCOUNT)...RM5 6LW
    ...THE SHOE SHOP........DN54 05Y
X102...THE SHOE SHOP........DN54 05Y

但是我只需要显示帐号也没有重复的地方,即如下所示

acc....custname.............postcode
B102...BILLYS SHOES.........LE54 2YZ
B104...BILLYS SHOES.........LE54 2YZ
    ...THE SHOE SHOP........DN54 05Y
X102...THE SHOE SHOP........DN54 05Y

代码:

SELECT *
FROM mailing
WHERE postcode IS NOT NULL AND postcode <> '' AND
postcode IN (SELECT postcode FROM mailing group by postcode HAVING COUNT(postcode) > 1)
ORDER BY postcode;

试图在帐号上使用另一个计数器,但根本没有获得任何数据

1 个答案:

答案 0 :(得分:0)

您可以在两种情况下使用NOT EXISTSEXISTS

SELECT m.* FROM mailing m
WHERE
  NOT EXISTS (
    SELECT 1 FROM mailing
    WHERE acc = m.acc AND custname <> m.custname
  )
  AND
  EXISTS (
    SELECT 1 FROM mailing
    WHERE postcode = m.postcode and acc <> m.acc
  )

如果您只想记录邮政编码重复的地方,但前提是它们用于不同的帐号,则仅使用EXISTS:

SELECT m.* FROM mailing m
WHERE
  EXISTS (
    SELECT 1 FROM mailing
    WHERE postcode = m.postcode and acc <> m.acc
  )