Error code 1824 mysql workbench

When I try to create the 'Project table I get this error Code: 1824. Failed to open the referenced table 'Employee'. My syntax: CREATE DATABASE IF NOT EXISTS Test; USE Test; CREATE TABLE IF NOT ...

When I try to create the ‘Project table I get this error Code: 1824. Failed to open the referenced table ‘Employee’.

My syntax:

CREATE DATABASE IF NOT EXISTS Test;
USE Test;

CREATE TABLE IF NOT EXISTS Customer (
CustomerID VARCHAR(7) NOT NULL,
CustomerName VARCHAR(50),
CustAdress VARCHAR(70),
CustEmail VARCHAR(50),
PRIMARY KEY (CustomerID)
);

CREATE TABLE IF NOT EXISTS Employee (
EmpID VARCHAR(7) NOT NULL,
EmpName VARCHAR(50),
Position VARCHAR(30),
EmpTimePrice INT(4),
PRIMARY KEY (EmpID)
);

CREATE TABLE IF NOT EXISTS Project (
ProjectNo VARCHAR(7),
ProjectName VARCHAR(50),
StartDate DATE,
ProjTimePrice INT(6),
CustomerID VARCHAR(7),
EmpID VARCHAR(7),
PRIMARY KEY (ProjectNo),
FOREIGN KEY (EmpID) REFERENCES Employee (EmpID),
FOREIGN KEY (CustomerID) REFERENCES Customer (CustomerID) 
);

CREATE TABLE IF NOT EXISTS ProjectWork (
ProjectNo VARCHAR(7),
EmpID VARCHAR(7),
PWDATE DATE,
HoursWorked INT(5),
FOREIGN KEY (ProjectNo) REFERENCES Project (ProjectNo),
FOREIGN KEY (EmpID) REFERENCES Employee (EmpID)
);

The names look correct to me and I have referenced the foreign key so I don’t understand why I get this error. Any help would be appreciated, thanks.

Issue

I am building a database for a school project, but for some reason I cannon make a foreign key reference between 2 tables (only those 2). My project has 14 tables and it works fine for all the others.

The tables are made like:

create table degree(
    title varchar(50),
    idryma varchar(40),
    bathmida enum('High School', 'Univercity', 'Master', 'PHD'),
    constraint degree_id primary key (title, idryma)
);

create table has_degree(
    degree_title varchar(50),
    degree_idryma varchar(40),
    employee_username varchar(12),
    acquisition_year year(4),
    grade float(3,1),

    constraint has_degree_id primary key (degree_title, degree_idryma, employee_username)
);

And then I try to alter the table so that I make the foreign key connections:

alter table has_degree add foreign key (degree_title) references degree(title);
alter table has_degree add foreign key (degree_idryma) references degree(idryma);

But I keep on getting

Error Code: 1824. Failed to open the referenced table ‘degree’

I have tried to make them like that:

create table degree(
    title varchar(50),
    idryma varchar(40),
    bathmida enum('High School', 'Univercity', 'Master', 'PHD'),
    constraint degree_id primary key (title, idryma)
);

create table has_degree(
    degree_title varchar(50),
    degree_idryma varchar(40),
    employee_username varchar(12),
    acquisition_year year(4),
    grade float(3,1),

    foreign key (degree_title) references degree(title),
    foreign key (degree_idryma) references degree(idryma),
    
    /*employee is an other table that I use and that works just fine*/

    foreign key (employee_username) references employee(employee_username),
    constraint has_degree_id primary key (degree_title, degree_idryma, employee_username)
);

But the only thing that changes is that I get

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint ‘has_degree_ibfk_2’ in the referenced table ‘degree’

Solution

The columns in your foreign key in table has_degree must be the same as the columns in the primary key of the referenced table degree.

In this case, the primary key of degree consists of two varchar columns.

So the foreign key in has_degree that references it must also be only two varchar columns, and values in those columns in has_degree must match exactly the values in a row of degree.

You defined the foreign key this way:

foreign key (degree_title) references degree(title),
foreign key (degree_idryma) references degree(idryma),

But that’s two foreign keys, each having a single column. You need one foreign key with two columns:

foreign key (degree_title, degree_idryma) references degree(title, idryma),

Answered By – Bill Karwin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

I have a MySQL 5.7.x dump with about 12GB that I try to import into a newly installed MySQL 8.0.x local instance.

mysql -u username -p test < DB-210508.sql  

The import starts but fails with the following message:

ERROR 1824 (HY000) at line 518: Failed to open the referenced table 'table-name'

I am wondering why there is a problem with foreign keys and if it is not more due to the fact that I am importing into 8.0.x

The MySQL 8.0.x instance is configured like this:

[mysqld]
default_authentication_plugin= mysql_native_password
innodb_buffer_pool_size = 8G
innodb_buffer_pool_instances = 32
innodb_buffer_pool_chunk_size = 134217728
collation_server        = utf8_unicode_ci
character_set_server    = utf8

What could be the reason for the failed import?

asked May 8, 2021 at 15:19

merlin's user avatar

2

This error happens when you have a classic “chicken and egg” problem. The most common situations for this would be:

  • populating a self-referencing table where a lower ID requires the existence of a higher ID
    ⇢ a good example of this would be an Employee table where record 33 had a manager with an ID of 999. 33 could not be recorded until 999 existed in the table.
  • populating a table that depends on another table that has not yet been created
    ⇢ this can happen when you have an Employee table that has references to User, but User isn’t created until after Employee.

The error you received was:

… Failed to open the referenced table 'table-name'

This points to the second item as being the most likely culprit.

The simplest way to resolve this would be to remove the foreign key checks when importing the data, then restore the checks after the import is complete. You can do this be editing your 12GB .sql file to have this at the very start:

SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS;
SET FOREIGN_KEY_CHECKS = 0;

Then, at the very end of the import file:

SET FOREIGN_KEY_CHECKS = @OLD_FOREIGN_KEY_CHECKS;

Note: With the foreign key check disabled, there is a possibility of recording bad data. If this is something you need to avoid for regulatory purposes, do not follow this “quick” merhod.

answered May 8, 2021 at 16:00

matigo's user avatar

matigomatigo

1,8831 gold badge4 silver badges15 bronze badges

#mysql #laravel #migration #laravel-8

Вопрос:

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

   IlluminateDatabaseQueryException 

  SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'admin_table' (SQL: alter table `blogs_table` add constraint `blogs_table_admin_id_foreign` foreign key (`admin_id`) references `admin_table` (`id`))

 

пожалуйста, помогите мне решить эту проблему, я не понимаю, где я ошибся..

структура таблицы миграции введите описание изображения здесь

2021_08_11_170129_create_Blogs_table.php

 <?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('blogs_table', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('price');
            $table->string('country');
            $table->longText('description');
            $table->integer('rating');
            $table->longText('image');
            $table->unsignedInteger('admin_id');
            $table->foreign('admin_id')->references('id')->on('admin_table');
            $table->timestamps();
            //$table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('blogs_table');
    }
}

 

2021_08_12_121933_create_admin_table.php

 <?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;

class CreateAdminTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('admin_table', function (Blueprint $table) {
            $table->id();
            $table->string('firstName');
            $table->string('lastName');
            $table->string('email')->unique();
            $table->string('mobile');
            $table->string('password');
            $table->timestamps();
            //$table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('admin_table');
    }
}

 

Комментарии:

1. Ошибка довольно очевидна… Как вы можете ссылаться на другую таблицу, которая не была создана ? Сначала вы создаете blogs_table , а затем создаете admin_table , поэтому при создании blogs_table и запуске миграции она не будет существовать admin_table для ссылки…

Ответ №1:

Сначала вы пытаетесь запустить миграцию в таблице блогов, а затем запустите миграцию в таблице администратора.

Миграция Laravel использует метку времени в начале файла, чтобы решить, какая миграция должна быть перенесена первой в последовательности.

Убедитесь, что вы сначала создали таблицу администратора перед таблицей блога (это также относится ко всем таблицам, на которые есть ссылки). Или просто переименуйте файл (измените метку времени), например:

 2021_08_12_121933_create_admin_table.php
2021_08_11_170129_create_Blogs_table.php
 

К этому:

 2021_08_11_121933_create_admin_table.php
2021_08_12_170129_create_Blogs_table.php
 

Затем запустите php artisan migrate:fresh , чтобы обновить миграцию.

Комментарии:

1. @DevopsTraining вы не должны получать ошибки с этим решением, вам нужно переименовать оба файла

2. Вы также правы, это также нормально, если мы переименуем оба файла.

Ответ №2:

Когда вы настраиваете внешний ключ $table->foreign('admin_id')->references('id')->on('admin_table'); , таблица admin_table еще не существует.

Измените имя миграции таблицы admin_table, которая будет запущена перед именем страницы блога.

2021_08_11_121933_create_admin_table.php

вместо

2021_08_12_121933_create_admin_table.php

Hello everyone, 

I am facing an issue with my table migration I am getting a weird error while running 

php artisan migrate:fresh

The error is 

 SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'blog' (SQL: alter table `blog_comments` add constraint `blog_comments_postid_foreign` foreign key (`postID`) references `blog` (`id`) on delete cascade) at C:laravelwp4worldvendorlaravelframeworksrcIlluminateDatabaseConnection.php:671 667| // If an exception occurs when attempting to run a query, we'll format the error 668| // message to include the bindings with SQL, which will make this exception a 669| // lot more helpful to the developer instead of just the database's errors. 670| catch (Exception $e) { > 671| throw new QueryException( 672| $query, $this->prepareBindings($bindings), $e 673| ); 674| } 675|

Here is the migration file 

<?phpuse IlluminateDatabaseMigrationsMigration;use IlluminateDatabaseSchemaBlueprint;use IlluminateSupportFacadesSchema;class CreateBlogsTable extends Migration{ /** * Run the migrations. * * @return void */ public function up(){ Schema::create('blog', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('title'); $table->string('post_url'); $table->string('img_path')->nullable(); $table->longtext('content'); $table->string('tags'); $table->string('status')->default(0); $table->string('public_date', 30); $table->unsignedBigInteger('ownerID'); $table->foreign('ownerID')->references('id')->on('admins')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('blog'); }}

Does anyone know what is the issue about? I had checked everything and there is no error or any missing thing?
Thank you in advance

System Info:

  • OS: Ubuntu 19.10
  • Laravel Version: 7.0
  • PHP Version: 7.3.11-0ubuntu0.19.10.4
  • MySQL Version: mysql Ver 8.0.19-0ubuntu0.19.10.3 for Linux on x86_64 ((Ubuntu))

I am building a small Laravel application and am having an issue with MySQL and relationships. When I try to run my migrations, this is the error I get:

SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'customers_table' (SQL: alter table `customer_contacts` add constraint `customer_contacts_customer_id_foreign` foreign key (`customer_id`) references `customers_table` (`id`))

And these are the two migration files in question.

customer table and migration:

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateCustomersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->id();

            $table->string('company_name', 50);
            $table->string('phone_number', 20)->nullable();
            $table->string('fax_number', 20)->nullable();
            $table->string('address_line_1', 75)->nullable();
            $table->string('address_line_2', 75)->nullable();
            $table->string('city', 75)->nullable();
            $table->string('state', 30)->nullable();
            $table->string('zip', 11)->nullable();
            $table->string('industry', 100)->nullable();
            $table->text('notes')->nullable();

            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('customers');
    }
}

And thecustomer_contacts table and migration:

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateCustomerContactsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('customer_contacts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('customer_id')->constrained('customers_table');
            $table->string('name', 50);
            $table->string('title', 50);
            $table->string('project', 50);
            $table->string('email', 50);
            $table->string('mobile_phone', 20);
            $table->string('work_phone', 20);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('customer_contacts');
    }
}

And this is the relevant section from mydatabase.php file:

...

'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => 'InnoDB',
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

...

I tried changing my database to SQLite to see if I get the same error and I do not, only MySQL creates this error.

Find the answer in similar questions on our website.

Понравилась статья? Поделить с друзьями:
  • Error code 1822 mysql
  • Error code 1801
  • Error code 18005
  • Error code 18001
  • Error code 1753