PHP MyAdmin Altering an existing table to create foreign keys - mysql

first post so very sorry if this seems like an obvious answer. Here's the premise of my problem. I have a database I am managing using PhpMyAdmin. I have a table called "Schedules" and want the id of the drivers on the schedule to be a foreign key that references a larger table "Users" where the ID column in this table is a primary key. Here is what i tried:
ALTER TABLE `Schedules`
ADD CONSTRAINT `FK_DriverID`
FOREIGN KEY (`Driver_ID`)
REFERENCES `users`(`ID`);
However, i get this error:
1005 - Can't create table 'Scheduler.#sql-3b7_3b9d' (errno: 150)
(Details…)
I am really at a loss with this error because im not trying to create any tables just alter an existing one. Thanks again and sorry if I butchered the formatting.

This mainly is due to a wrong primary key reference in your table.
Usually this means the key you are referencing does not exist / there might be difference in datatype between the FOREIGN KEY and the REFERENCED column / or there might be difference in column name.
Make sure that
you have a column named ID in users table
Driver_ID column have the same data type as ID column in Users table. Make sure both are exactly of the same data type.
Refer this for more information

Related

How to create table B like A with foreign key definitions?

I am able to create table sales_order in database archived_db with the same schema as sales_order table from main database prod_db using below query:
CREATE TABLE archived_db.sales_order LIKE prod_db.sales_order
It is working fine and creating sales_order table in archived_db with same table structure as in prod_db. One thing that is not copied/created is the foreign key.
so, my question is, is it possible to create table B using schema of table A with the same foreign_keys?
You can use this:
SHOW CREATE TABLE prod_db.sales_order
This shows the table definition in the syntax of a CREATE TABLE statement.
Capture the result of this into a string, and then run that string as an SQL statement.
I would suppose that CREATE TABLE <B> LIKE <A> doesn't support foreign keys because foreign keys are a feature that depends on the storage engine. The engine-independent metadata does not store foreign key definitions. This is one of the unexpected consequences of MySQL's strange history and architecture of pluggable storage engines.
Re your comment:
ERROR 1215 (HY000): Cannot add foreign key constraint
Does the parent table exist in the archived db schema in which you are creating the copy table? I imagine the foreign key definition does not qualify the table name, and assumes that the parent table is in the same schema as the sales_order table.
If you need to specify which schema the foreign key references, it's probably best to create the table using CREATE TABLE LIKE as you were before, and then add foreign key(s) using ALTER TABLE.

MySQL 5.5 errno: 150 "Foreign key constraint is incorrectly formed"

There are plenty of questions regarding this error but I can't seem to find any similar scenario to what I have.
My 1st table (users):
My 2nd table (colleges):
I am trying to alter 1st table and add a foreign key that references id of a 2nd table:
ALTER TABLE users
ADD CONSTRAINT FOREIGN KEY (collegelinkId)
REFERENCES databaseName.colleges (id);
Which fails with error (errno: 150 "Foreign key constraint is incorrectly formed").
The only parameter that is different between these two tables is auto_increment. However, I can not add auto_increment to my users table collegelinkId column since its id is already set to auto_increment.
We would expect to see this error if the types of the primary and foreign key did not match exactly. While both appear to be integer with a width of 1, my guess here is that one of the INT columns in the key relationship is unsigned, while the other is signed. A possible fix would be to make both columns unsigned:
ALTER TABLE users MODIFY collegelinkId INT(10) UNSIGNED NOT NULL;
ALTER TABLE college MODIFY id INT(10) UNSIGNED NOT NULL;
Edit:
I was wrong, as evidenced by your latest comments under my answer. Another possibility is that you created your two tables using different database engines. For example, if you created users using InnoDB, but college using MyISAM, you could still get this error. To fix this, change the engine(s) on the tables to the same type.
Note that yet another possibility would be that the two columns had different collations. But, that's really a moot point here, since both columns are numeric, not text.
Since the columns are of the same type, it's worth to check the engine type as #Tim Biegeleisen suggested.
Changing engine type fixed the issue.
ALTER TABLE users
ENGINE=InnoDB;
Verify that the datatypes match (except for PRIMARY KEY).
Verify that both tables are ENGINE=InnoDB.
Even after that, error 150 can still occur. 3 ways around it:
Disable FKs while creating the tables, then re-enable.
CREATE TABLEs without FKs, then ALTER ... ADD ... FKs
Be sure the do the CREATEs in just the right order.
A side note: In INT(2), the (2) is irrelevant. All INTs are 4 bytes.

MySQL : Foreign Key

I have two tables inside my MySQL database which consists of awards and members. I want to set member_name as a foreign key into awards table instead of member_id.
I have set member_name as UNIQUE inside the members table and trying to set it as foreign key but I'm getting an error:
Cannot add or update a child row: a foreign key constraint fails
Can someone tell me why I'm getting this error?
Your error is showing that you are trying to insert a child row while its corresponding row does not exist in its master table. So first insert in master table then in child.
If this is not the case then you can also check that it seems you are trying to create foreign key member_name as string in member table with member_id as int in award table, while to make foreign key relationship both fields data type should be same.
If this is not the case then share your table structure and your alter query to make foreign key.
Note: Foreign key always perform with better performance by int data type than string. So you should keep member_id instead of member_name if there is no specific reason of it.
It would be easier to answer this question if you provided more details on
both table structures.
In any case, the error would most likely indicate that there’s a record in the existing data set that would violate the Foreign Key constraint, i.e., a member_name in the awards table which doesn’t exist in the members table.

can't add foreign key in mysql?

I used MySQL workbench to add a foreign key in a table, but some strange error happened, this is the SQL statement:
ALTER TABLE `tansung`.`Declaration` ADD COLUMN `goodsId` INT(11) NOT NULL AFTER `declarationId` ,
ADD CONSTRAINT `goodsId`
FOREIGN KEY (`goodsId` )
REFERENCES `tansung`.`Goods` (`goodsId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
, ADD INDEX `goodsId` (`goodsId` ASC) ;
When i click apply, the surprise comes out!
ERROR 1005: Can't create table 'tansung.#sql-1b10_1' (errno: 150)
SQL Statement:
ALTER TABLE `tansung`.`Declaration` ADD COLUMN `goodsId` INT(11) NOT NULL AFTER `declarationId` ,
ADD CONSTRAINT `goodsId`
FOREIGN KEY (`goodsId` )
REFERENCES `tansung`.`Goods` (`goodsId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
, ADD INDEX `goodsId` (`goodsId` ASC)
ERROR: Error when running failback script. Details follow.
ERROR 1050: Table 'Declaration' already exists
SQL Statement:
CREATE TABLE `Declaration` (
`declarationId` int(11) NOT NULL,
PRIMARY KEY (`declarationId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
I can't find out any mistake in logic, even can't understand the error, please give me a help.
All foreign key names throughout the database must be unique. If you already have a foreign key named 'goodsId', even on another table, you will receive this error.
If the related columns do not have exactly the same type (e.g. INT) and constraints (UNIQUE and such), you will receive that error.
It can happen because of many reasons. Following are some of the common reasons. You can also say syntactical errors, because of which these kinds of error are thrown.
If the FK (Foreign Key) table Engine is using MyISAM and PK (Primary Key) table Engine is using InnoDB. MyISAM does not support foreign key constraints. So, you might want to converting your linking table to InnoDB.
All foreign key names throughout the database must be unique. If you already have a foreign key constraint with the same name, even on another table, you will receive this error.
If the related columns do not have exactly the same data typetype (e.g. INT) and constraints (UNIQUE and such), you will receive that error.
I'm getting this error when the table being linked to (in your case, Goods) is stored using MyISAM, and the table you're adding the index to (in your case, Declarations) is stored using InnoDB.
You can tell this from the files in the database directory. MyISAM tables will have files like:
table_name.frm
table_name.MYD
table_name.MYI
The InnoDB table will just have:
table_name.frm
MyISAM does not support foreign key constraints. I would suggest converting your Goods table to InnoDB (though, have a look at the documentation first and do some basic research):
ALTER TABLE Goods ENGINE=INNODB;
After making this change, my ADD INDEX operation completed successfully.
Like the others have said, first make sure the types of the two columns are the same and the database supports it. After that, make sure that the columns that hold the keys to the other tables are valid.
I had a problem where I was adding the constraint to an existing column with data in it, and that data didn't match any of the primary keys in the other table so the attempt to create the relationship would fail. Fixing it involved updating all the columns to make sure my column data matched up with the constraint I was trying to make.
I discovered that when trying to do this in phpMyAdmin that tables that had a hyphen in the name would only allow one FK and then give errors. I have no idea why but it was easy enough to work around I simply remade the
CREATE TABLE `something_new` LIKE `something-old`;
DROP TABLE `something-old`;
YMMV.
The type definitions of Goods.goodsId and Declarations.goodsId must be identical, or you will get the errno: 150.
Make sure they are both the same data type, which looks to be goodsId INT(11) NOT NULL in the Declarations table. What is the CREATE TABLE statement for Goods?
I had the same problem. It seems that there was some data in the child table that was not present in the parent table. You can do an outer join to see the differences and you can assign a valid id for non-matching rows or delete them:
DELETE FROM books
WHERE NOT EXISTS (
SELECT * FROM users
WHERE books.user_id = users.id
)
Errno 150 has a lot of causes. If you have SUPER privileges, you should try using
SHOW ENGINE INNODB STATUS
and that will tell you what the cause was. If you don't have SUPER privileges, you need to just go through all the possible causes. You can find how to use the SHOW INNODB STATUS and a list of all the causes here:
MySQL Foreign Key Errors and Errno 150
When I got that error it was becuase I was trying to update a table that already had data int it and the data didn't meet the FK restrictions.
A fourth possible problem (to the three proposed by abhijitcaps) is that you didn't make the column you are referencing to a primary key.

MySQL FK syntax: insert column called practice into table cred_insurances that is FK to table practices

I need to insert a column called "practice" into table "cred_insurances" that is a FK referencing table "practices" PK "id"
You will need to ensure that your MySQL table is using the InnoDB engine, by running the following from the mysql prompt.
show create table cred_insurances
the output will include (towards the bottom) the text ENGINE=.... If it is not InnodDB, then you will first need to convert it using the following SQL. You may need to do this to the parent table as well.
ALTER TABLE cred_insurances ENGINE=InnoDB
Then you can add a column and a foreign key constraint with the following command:
ALTER TABLE cred_insurances
ADD practice INT,
ADD CONSTRAINT fk_practice
FOREIGN KEY (practice) REFERENCES practices (ID)
If you are having difficulties with errors whilst adding a foreign key, try the following command to get more detailed information on the error.
SHOW ENGINE INNODB STATUS