我有一个MySQL
地址表,其中包含以下列:
STATE, ZIPCODE, FLAG
给定state/zipcode
组合可以有多行。我想确保对于每个给定的state/zipcode
组合,只有一行有FLAG = 'P'
。
我知道如何检查多行:
SELECT state, zipcode, flag, count(*) as numrecs
FROM addresses
WHERE flag = 'P'
group by state, zipcode
having numrecs > 1;
如何检查零条目 - state/zipcode
组合中没有flag = 'P'
的行?
答案 0 :(得分:1)
你走在正确的轨道上,只需使用条件聚合:
SELECT state, zipcode, flag, count(*) as numrecs
FROM addresses
GROUP BY state, zipcode
HAVING coalesce(sum(flag = 'P'), 0) <> 1
或者,如果您愿意:
HAVING coalesce(sum(flag = 'P'), 0) = 0 or sum(flag = 'P') > 1
如果coalesce()
可以是flag
,并且给定的州/邮政编码组合只有NULL
个标记,则需要NULL
。
答案 1 :(得分:0)
此查询应该为您提供违反标准的内容:
SELECT STATE, ZIPCODE, SUM(FLAG_COUNTER)
FROM (SELECT *, IF(FLAG='P', 1, 0) AS FLAG_COUNTER FROM addresses) tableWithCounter
GROUP BY STATE, ZIPCODE
HAVING SUM(FLAG_COUNTER) != 1