I know a primary key should be unique. But i am creating a database for an estate agency where the post code is the Primary Key for the Address table. But if a property is for sale/rent and it is in a block of flats many properties will have the same post code. How do i make it Not Uniqe whilst keeping the PostCode as the PK? thank u
my code so far:
CREATE TABLE `Properties` (
`PropertyID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`Property Type` varchar(20) NOT NULL,
`PostCode` varchar(8) NOT NULL,
`Bedrooms` tinyint(2) DEFAULT NULL,
`Bathrooms` tinyint(2) DEFAULT NULL,
`Ensuite` tinyint(1) DEFAULT NULL,
`Kitchen` tinytext,
`LivingRoom` tinytext,
`DiningRoom` tinytext,
`UtilityRoom` tinytext,
`Conservatory` tinytext,
`Garage` tinytext,
`Garden` tinytext,
`Furnished` tinytext,
`Type` char(15) NOT NULL,
PRIMARY KEY (`PropertyID`),
KEY `Property Type` (`Property Type`),
KEY `PostCode` (`PostCode`),
CONSTRAINT `Properties_ibfk_2` FOREIGN KEY (`PostCode`) REFERENCES `Address` (`PostCode`),
CONSTRAINT `Properties_ibfk_1` FOREIGN KEY (`Property Type`) REFERENCES `PropertyType` (`Property Type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `Address` (
`PostCode` varchar(8) NOT NULL,
`HouseN` text NOT NULL,
`AddL1` varchar(25) NOT NULL,
`AddL2` varchar(25) DEFAULT NULL,
`AddL3` varchar(25) DEFAULT NULL,
`County` char(20) NOT NULL,
PRIMARY KEY (`PostCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Primary keys are unique by deifinition; a better approach would be to have either a surrogate key (like an auto numbered value), or a composite key which covers multiple columns, such as the postal code and property name/number.
Be aware of course that postcodes can change over time for a given property in some countries (like the UK); and because of this, I'd advocate the surrogate key approach.
In database design there are 2 different sides/classes/styles.
As you see, these are these are 2 completely opposing sides. Personally i would recommend the first, but you are free to choose yourself of course. Its a smart thing tho to try to stick to a single style within a database.
In the problem you mentioned the primary key was defined (by the customer) as the postal code. You now walk into the problem that the postal code doesn't uniquely identify each row: Conclusion: Your primary key is incorrectly defined.
Solution: What Rowland said: either use a surrogate key (1st class), in fact you already have one: PropertyID. 2nd Option: add a field/fields to the key so that it will uniquely identify each row, such as house/street number.
The main reason for setting a PrimaryKey is to make each record unique. In your case, post code is not unique, I recommend not to set it as the PK. Instead you can make a surrogate key.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.