Error in putting FK in table

0

I have a problem with my Database. I try to put an FK in my general table that is as PK in my table Rates, try the following way and I mark the following error.

  

Table where I have the PK

  

Table where I want the PK (I already have the attribute but can not put it   as FK)

With this query I wanted to put the attribute as FK but it marks me the following error.

mysql> ALTER TABLE general ADD FOREIGN KEY (id_tarifa) REFERENCES tarifas(id_tarifa);
ERROR 1215 (HY000): Cannot add foreign key constraint
    
asked by Javier fr 26.11.2018 в 17:29
source

1 answer

1

Test tables: (what if you would have to set the records, as you comment the tables have data, if you want to make id_tariff is fk and in general you have a id_tarifa but in the tariff table that id does not exist is going to give an error because it will not find the key foreigner)

        use prueba;

        create table tarifa(
            id_tarifa int not null auto_increment,
            proveedor nvarchar(50) not null,
            desc_tar nvarchar(50) not null,
            primary key (id_tarifa)
        );

        create table general(
            id_general int not null auto_increment,
            nombre nvarchar(50) not null,
            id_tarifa int not null,
            primary key (id_general),
            FOREIGN KEY (id_tarifa)
            REFERENCES tarifa (id_tarifa)
        );

Now creating it without FK and using the line you pass you also works:

        use prueba;

        create table tarifa(
            id_tarifa int not null auto_increment,
            proveedor nvarchar(50) not null,
            desc_tar nvarchar(50) not null,
            primary key (id_tarifa)
        );

        create table general(
            id_general int not null auto_increment,
            nombre nvarchar(50) not null,
            id_tarifa int not null,
            primary key (id_general)
        );


        ALTER TABLE general ADD FOREIGN KEY (id_tarifa) REFERENCES 
        tarifa(id_tarifa)

Now if the tables have data to be able to create the FK you need all the data, look at the following example, I create the table without FK charge two data in general and one only in tariff, one of the data in general refers to rate 2 but this does not exist in the tariff table, now I execute the command to do the FK and there I get an error I do not give me because it does not find all the references

Try this query (fit the exact names of your tables)

SELECT G.id_general, T.id_tarifa from GENERAL G LEFT JOIN TARIFA T ON 
T.id_tarifa = g.id_tarifa

In my example it shows me that there are two registers but for register two there is no fee two, there is the error in my example

    
answered by 26.11.2018 / 17:51
source