如何存储CarName一次并防止重复存储?

时间:2013-08-15 03:59:27

标签: mysql database relationship create-table

我有一个名为Person的表,其中包含以下属性:

enter image description here

我想实现一个名为Car的表,该表将保存有关Person驱动的汽车的信息。我想以一种方式实现它,如果多个用户驾驶“丰田卡罗拉”,那么“丰田卡罗拉”应该只作为一个字符串存储一次。我也认为不是每个人都只拥有一辆汽车,这是公平的。这些条目将定期记录,但不同的Car记录只能达到5000。到目前为止,我已经完成了以下操作但如何实现属性,如果多个用户拥有相同的汽车,我将保存ModelNames一次。

Car

CREATE  TABLE `Car` (
`idCar` MEDIUMINT UNSIGNED  AUTO_INCREMENT ,
`ModelName` varchar(80),
`idPerson` INT NOT NULL,
PRIMARY KEY (`idCar`) ,
FOREIGN KEY (`idPerson`)    REFERENCES `Person` (`idPerson`) 
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE=InnoDB;

UPDATE Car, Person
Set Car.idPerson = Person.idPerson
WHERE Car.idPerson = Person.idPerson;

INSERT INTO Car VALUES (1, 'Toyota Corolla', 1);
INSERT INTO Car VALUES (2, 'Mazda 6', 1);
INSERT INTO Car VALUES (3, 'Toyota Corolla', 2);
INSERT INTO Car VALUES (4, 'Pulsar GTI', 3);


SELECT DISTINCT Car.idCar ,Car.ModelName,  Person.FullName,  Person.idPerson
FROM Person, Car
WHERE Car.idPerson = Person.idPerson
Order by Car.idCar;

1 个答案:

答案 0 :(得分:2)

我认为您需要查看多对多关系设计。

让我们说

Person
- PersonID -> Primary Key
- Surname
- FirstName
- Title
- etc

Car
- CarID -> Primary Key
- CarType
- CarMake
- YearModel
- etc

PersonCars
- PersonID -> Foreign Key to Person.PersonID
- CarID = > Foreign Key to Car.CarID

这将允许您定义一次汽车定义,并多次链接。

然后您可以选择如下

SELECT  *
FROM    Person p INNER JOIN
        PersonCars pc   ON  p.PersonID = pc.PersonID INNER JOIN
        Car c   ON  pc.CarID = c.CarID