ОШИБКА 1075 может быть только один автоматический столбец, и он должен быть определен как ключ. Помогите определить, как мне сохранить внешний ключ ReportID - PullRequest
0 голосов
/ 02 ноября 2019

Почему это не работает ?? Мне нужен второй auto_increment, так как я использую его в качестве первичного ключа в другой таблице. Я хочу, чтобы правонарушения были непосредственно связаны с сообщениями, которые они нашли в

Create table ReportsFiled (
    ReportID INT(10) NOT NULL AUTO_INCREMENT,
    DateandTime DATETIME NOT NULL,
    VehicleID VARCHAR(10) NOT NULL,
    LicenseNumber VARCHAR(16) NOT NULL,
    OffenceCommitted VARCHAR(255) NOT NULL,
    ReportStatement VARCHAR(255) NOT NULL,
    constraint pkReportsFiled primary key (ReportID, VehicleID),
    constraint fkReportsFiledVehID foreign key (VehicleID) references Vehicles(VehicleID),
    constraint fkReportsFiledLicNum foreign key (LicenseNumber) references People(LicenseNumber)
    ) ENGINE=InnoDB ; 

Insert into ReportsFiled 
(ReportID, DateandTime, VehicleID, LicenseNumber, OffenceCommitted, ReportStatement)
Values 
(NULL, '2019-01-20 10:30:00', 'FD13 5TY', 'WRIGY96543867FD4', 'Moderate Speeding', 'Speeding in a residential area, given points and fine appropriate to the nature of the offence'),
(NULL, '2019-03-12 16:30:00', 'FT17 8HU', 'BARTO87252867BO4', 'Dangerous driving and Moderate Speeding', 'Driving recklessly in a residential area and driving above the speed limit, 3 points and £350'),
(NULL, '2019-05-28 12:23:00', 'SJ12 J8S', 'SMITH54398866QW4', 'Dangerous driving', 'Taking a corner too fast with no indication, 3 points given but no fine issued'),
(NULL, '2019-01-01 11:21:00', 'FT17 8HU', 'BARTO87252867BO4', 'Moderate Speeding', 'Driving at 42mph in a 30mph zone, 3 points and a £200 fine'),
(NULL, '2019-03-30 14:26:00', 'QW15 X4U', 'SPENC32975368DW8', 'Driving dangerously under the influence of alcohol', 'Licence ban and £2,500 fine'),
(NULL, '2019-08-21 22:14:00', 'FT17 8HU', 'BARTO87252867BO4', 'Driving while using a mobile device', 'Driving using a mobile device, 6 points and £500 fine') ;

Create table Offences (
    OffenceID INT(10) NOT NULL AUTO_INCREMENT,
    OffenceStatement VARCHAR(255) NOT NULL, 
    MaximumFine VARCHAR(100),
    ReportID INT(10) NOT NULL AUTO_INCREMENT,
    constraint pkOffences primary key (OffenceID, ReportID),
    constraint fkOffencesReID foreign key (ReportID) references ReportsFiled(ReportID)
    ) ENGINE=InnoDB ;

Insert into Offences
(OffenseID, OffenceStatement, MaximumFine, ReportID)
Values
(NULL, 'Moderate Speeding', '3-6 points and £0-£200 fine', NULL),
(NULL, 'Driving under the influence of alcohol', 'Licence ban and £2,500 fine', NULL),
(NULL, 'Extreme Speeding', 'Licence ban and £2,000 fine', NULL),
(NULL, 'Dangerous driving', '3 points and £0-£500', NULL),
(NULL, 'Driving while using a mobile device', '6 points and £500 fine', NULL) ; 

1 Ответ

1 голос
/ 02 ноября 2019

Я думаю, что вы смешиваете здесь понятие первичный ключ и внешний ключ .

Первичный ключ auto_incremented дает уникальный целочисленный идентификатор для каждой записи.

Внешний ключ определяет отношение, в котором каждое значение в ссылочном столбце таблицы должно присутствовать в указанном столбце другой таблицы. Столбцы внешнего ключа не auto_incremented. Столбец может быть следующим.

Чтобы ваш проект имел смысл (и был принят механизмом MySQL), вам нужно сделать автоматически увеличиваемый столбец каждой таблицы первичным ключом и определить соответствующий внешнийключи.

Обратите внимание:

create table ReportsFiled (
    -- primary key
    ReportID int(10) not null primary key auto_increment,
    DateandTime datetime not null,
    VehicleID varchar(10) not null,
    LicenseNumber varchar(16) not null,
    OffenceCommitted varchar(255) not null,
    ReportStatement varchar(255) not null,
    -- foreign key to the Vehicle table
    constraint fkReportsFiledVehID
        foreign key (VehicleID) references Vehicles(VehicleID),  
    -- foreign key to People table
    constraint fkReportsFiledLicNum
        foreign key (LicenseNumber) references People(LicenseNumber)
) engine = InnoDB; 


create table Offences (
    -- primary key
    OffenceID int(10) not null auto_increment primary key
    OffenceStatement varchar(255) not null, 
    MaximumFine varchar(100),
    ReportID int(10) not null auto_increment,
    -- foreign key to People table
    constraint fkOffencesReID
        foreign key (ReportID) references ReportsFiled(ReportID)
) engine = InnoDB ;

Примечания:

  1. Я подозреваю, что внешний ключ для People(LicenseNumber): равен LicenseNumberпервичный ключ таблицы People? Если нет, то имейте в виду, что этот столбец должен быть хотя бы проиндексирован (либо сам по себе, либо в первой позиции составного индекса). Или просто рассмотрите возможность обращения к первичному ключу People вместо этого, что, по-видимому, является вашим намерением: вы всегда можете получить номер лицензии с помощью соединения при необходимости.

  2. Ссылка и ссылкастолбец должен иметь тот же тип данных

...