Ошибка MySQL: 1251 не может добавить внешний ключ

0

Первые 4 таблицы создаются отлично, таблицы транзакций запускаются в проблему. Я получаю ошибку 1215: не могу добавить внешний ключ. Я проверил перепроверенные типы данных и убедился, что все FK являются PK собственных таблиц. Что здесь не так?

CREATE SCHEMA FinalDB;

CREATE TABLE 'User' (
    userId int not null auto_increment primary key,
    first_name varchar(255) not null,
    last_name varchar(255) not null,
    address varchar(255) null,
    DOB date not null,
    availableBalance int not null default 0,
    currency varchar(20)
);

CREATE TABLE Verifications(
    userId int not null primary key,
    passport int null,
    ssn int null,
    license int null,
    constraint
    foreign key (userId)
    references User(userId)
);

CREATE TABLE Linked_Account(
    account_Id int not null, 
    userId int not null,
    routing int null,
    swift int null,
    primary key (userId, account_Id),
    constraint
    foreign key (userId) 
    references User(userId)
);

CREATE TABLE Wallet (
    userId int not null,
    walletId varchar(5) not null,
    coinAmount int not null default 0,
    netWorth int not null default 0,
    primary key(userId, walletId),
    constraint
    foreign key (userId)
    references 'User'(userId)
);

CREATE TABLE Transactions (
    transactionId int not null primary key auto_increment, 
    userId int not null,
    type varchar(30) not null,
    walletId varchar(5) not null,
    payment_method int null, #optional
    total int null, #optional
    quantity int not null,
    fee int null, #optional
    'date' date not null,
    sender varchar(50) null, #optional
    reciever varchar(50) null, #optional
    status varchar(20) not null,
    notes varchar(200) null, #optional
    constraint 
    foreign key (userId)
    references 'User'(userId) 
    ON DELETE CASCADE ON UPDATE CASCADE,
    constraint 
    foreign key (walletId)
    references Wallet(walletId)
    ON DELETE CASCADE ON UPDATE CASCADE,
    constraint
    foreign key (payment_method)
    references Linked_Account(account_id)

);

CREATE TABLE TransactionsExchange(
    transactionId int not null auto_increment primary key,
    userId int not null,
    currencyFrom int not null,
    currencyFromAmount int not null,
    currencyInto int not null,
    currencyIntoEquivalent int not null,
    notes varchar(200) null,
    'date' date not null,
    constraint
    foreign key (userId)
    references User(userId),
    constraint
    foreign key (currencyFrom)
    references Wallet(walletId),
    constraint
    foreign key (currencyInto)
    references Wallet(walletId)
);

Я смотрю онлайн для ответа, но обычно это связано с непоследовательными типами данных или необъявленными ПК. Я в основном пытаюсь сделать таблицу транзакций для записи различных разных данных в разных композициях. Использование бэкэнд-логики для обработки того, что требуется, а что нет, кроме нескольких значений по умолчанию.

Теги:
foreign-keys
mysql-error-1064

1 ответ

1
Лучший ответ

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

см. связанную запись здесь qaru.site/questions/915571/...

Попробуйте создать таблицу создания транзакций:

 CREATE TABLE Transactions (
            transactionId int not null primary key auto_increment, 
            userId int not null,
            type varchar(30) not null,
            walletId varchar(5) not null,
            payment_method int null, #optional
            total int null, #optional
            quantity int not null,
            fee int null, #optional
            'date' date not null,
            sender varchar(50) null, #optional
            reciever varchar(50) null, #optional
            status varchar(20) not null,
            notes varchar(200) null, #optional
            constraint 
            foreign key (userId)
            references 'User'(userId) 
            ON DELETE CASCADE ON UPDATE CASCADE,
            constraint
            foreign key (userId, walletId)
            references Wallet(userId, walletId)
            ON DELETE CASCADE ON UPDATE CASCADE,
            constraint
            foreign key (userId, payment_method)
            references Linked_Account(userId, account_id)

        );
  • 0
    Это сработало хорошо! Мне никогда не приходилось импортировать составные ключи как внешние ключи. Я просто предполагал, что каждый ключ должен быть объявлен индивидуально. Спасибо!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню