检查一对一关系 - SQL

时间:2015-03-26 11:38:03

标签: mysql sql

我已经下载了一个包含邮政编码和理事会的文件,我必须检查所有理事会是否与其理事会编号有一对一的关系(因为我可以将其存储在多个表中以节省空间)

现在的表格似乎是

councilnumber, int(3)
council, varchar(25)
zip, int(5)

如何检查它是否具有一对一的关系?

2 个答案:

答案 0 :(得分:1)

SELECT MIN(councilnumber), MAX(councilnumber), zip FROM tble group by councilnumber, council, zip HAVING MIN(councilnumber) <> MAX(councilnumber)

这将显示不良记录。如果您需要丢弃它们,请使用:

SELECT MIN(councilnumber), MAX(councilnumber), zip FROM tble group by councilnumber, council, zip HAVING MIN(councilnumber) = MAX(councilnumber)

顺便说一下,我不确定1to1是否是正确的关系。县里可以有很多拉链。实际上,一些拉链可以属于2个县(至少在美国)

在这种情况下,我建议您使用另一个表,该表将链接到ZIP和COUNTY以及它自己的ID。然后,您将能够从该ID获得ZIP和县,并且它将支持多对多关系

答案 1 :(得分:0)

SELECT councilnumber, count(council) as `count` FROM Councils group by councilnumber order by `count` desc

SELECT council, count(councilumber) as `count` FROM Councils group by council order by `count` desc

如果第一行的count高于1,则表示您有一个以上的理事会编号或理事会值