Getting 1005 MySQL error, not sure why - mysql

I am trying to create database tables and get them connected. I have ensured that my data types are identical. I also ensure that my tables are made before added the FK. Any advice would be greatly appreciated.
SQL query:
ALTER TABLE `Member` ADD FOREIGN KEY ( memberId ) REFERENCES `Order_Head` ( `memberId` ) ;
MySQL said: Documentation
#1005 - Can't create table 'test2.#sql-184c_63' (errno: 150) (Details...)
-- ---
-- Table 'Order_Head'
--
-- ---
DROP TABLE IF EXISTS `Order_Head`;
CREATE TABLE `Order_Head` (
`orderId` INTEGER NOT NULL AUTO_INCREMENT,
`memberId` INTEGER NOT NULL,
`date` DATE NOT NULL,
PRIMARY KEY (`orderId`, `memberId`)
);
-- ---
-- Table 'Member'
--
-- ---
DROP TABLE IF EXISTS `Member`;
CREATE TABLE `Member` (
`memberId` INTEGER NOT NULL AUTO_INCREMENT,
`userName` VARCHAR(50) NOT NULL,
`password` VARCHAR(50) NOT NULL,
`email` VARCHAR(100) NOT NULL,
`isAdmin` BOOLEAN NOT NULL DEFAULT false,
PRIMARY KEY (`memberId`)
);
-- ---
-- Foreign Keys
-- ---
ALTER TABLE `Member` ADD FOREIGN KEY (memberId) REFERENCES `Order_Head` (`memberId`);
-- ---
-- Table Properties
-- ---
ALTER TABLE `Order_Head` ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
ALTER TABLE `Member` ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

It may be because the foreign key you are trying to set up is a primary key and has AUTO_INCREMENT, maybe what you meant was:
ALTER TABLE `Order_Head` ADD FOREIGN KEY (memberId) REFERENCES `Member` (`memberId`);
Any particular reason you're not creating the foreign keys inside the CREATE TABLE statement? If not, then you should maybe do so too.

Related

Delete row from table:"Cannot delete or update a parent row:a foreign key constraint fails" is that a FOREIGN KEY problemm or CASCADE will do the job?

I want to delete a row from a "prods" table. Whenever I delete a row I want it to delete the rows from other tables associated with it.
Whenever I try to delete a row from "prods" using my PHP code - I get this error:
A Database Error Occurred
Error Number: 1451
Cannot delete or update a parent row: a foreign key constraint fails (`tools`.`keywords`, CONSTRAINT `keywords_ibfk_1` FOREIGN KEY (`key_prod`) REFERENCES `prods` (`prod_id`))
I got the same with the 'keywords' table - this was solved by deleting the rows that are "related" in the "data" table and just then - deleting the row from the 'keywords' table.
But when I encounter this issue again when deleting a row from the 'prods' table - I noticed that this cant be working like this and there have to be a much more efficient way to do this.
After googling a little bit I found out that I can maybe use "DELETE Cascade" - and it might cause problems (or deleting unwanted rows). I really don't know if it will - so I reaserched this a little bit more. Following other search results I have found this post:
Cannot delete or update a parent row: a foreign key constraint fails
Where the dude was told that the FOREIGN KEY wasn't done right - and he has to swap between them, which will solve his problem.
I am new to working with complex databases and I wanted to know if I am doing this the right way - all FOREIGN KEYs are done right, and if I use DELETE CASCADE will do the job right.
This is my DB dump structure (MySQL):
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
-- Table structure for table `prods`
--
CREATE TABLE `prods` (
`prod_id` int(11) NOT NULL,
`prod_name` varchar(255) NOT NULL,
`prod_aaa_id` varchar(255) NOT NULL,
`prod_bbb_id` varchar(255) NOT NULL,
`prod_get_installs` tinyint(1) NOT NULL,
`prod_user` int(11) NOT NULL,
`prod_client_email` varchar(255) NOT NULL,
`prod_client_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `prod_data`
--
CREATE TABLE `prod_data` (
`ad_id` int(11) NOT NULL,
`ad_prod` int(11) NOT NULL,
`ad_date` date NOT NULL,
`ad_aaa_inst` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `data`
--
CREATE TABLE `data` (
`id` int(11) NOT NULL,
`dat_id` int(11) NOT NULL,
`dat_date` date NOT NULL,
`dat_rank_aaa` int(11) NOT NULL,
`dat_traffic_aaa` float NOT NULL,
`dat_rank_bbb` int(11) NOT NULL,
`dat_traffic_bbb` float NOT NULL,
`dat_difficulty_aaa` float NOT NULL,
`dat_difficulty_bbb` float NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `keywords`
--
CREATE TABLE `keywords` (
`key_id` int(11) NOT NULL,
`key_word` varchar(255) NOT NULL,
`key_prod` int(11) NOT NULL,
`kay_country` text NOT NULL,
`key_is_wr` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`u_id` int(11) NOT NULL,
`u_name` varchar(255) NOT NULL,
`u_email` varchar(255) NOT NULL,
`u_password` varchar(255) NOT NULL,
`u_permission` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Table structure for table `weekly_report`
--
CREATE TABLE `weekly_report` (
`wr_id` int(11) NOT NULL,
`wr_prod_id` int(11) NOT NULL,
`wr_date` date NOT NULL,
`wr_date1` date NOT NULL,
`wr_date2` date NOT NULL,
`wr_date3` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `prods`
--
ALTER TABLE `prods`
ADD PRIMARY KEY (`prod_id`),
ADD KEY `prod_user` (`prod_user`),
ADD KEY `prod_user_2` (`prod_user`);
--
-- Indexes for table `prod_data`
--
ALTER TABLE `prod_data`
ADD PRIMARY KEY (`ad_id`),
ADD KEY `ad_prod` (`ad_prod`);
--
-- Indexes for table `data`
--
ALTER TABLE `data`
ADD PRIMARY KEY (`id`),
ADD KEY `dat_id` (`dat_id`);
--
-- Indexes for table `kas`
--
ALTER TABLE `kas`
ADD PRIMARY KEY (`kas_id`);
--
-- Indexes for table `keywords`
--
ALTER TABLE `keywords`
ADD PRIMARY KEY (`key_id`),
ADD KEY `key_prod` (`key_prod`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`u_id`),
ADD KEY `u_id` (`u_id`);
--
-- Indexes for table `weekly_report`
--
ALTER TABLE `weekly_report`
ADD PRIMARY KEY (`wr_id`),
ADD KEY `wr_prod_id` (`wr_prod_id`),
ADD KEY `wr_prod_id_2` (`wr_prod_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `prods`
--
ALTER TABLE `prods`
MODIFY `prod_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23;
--
-- AUTO_INCREMENT for table `prod_data`
--
ALTER TABLE `prod_data`
MODIFY `ad_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `data`
--
ALTER TABLE `data`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3754;
--
--
-- AUTO_INCREMENT for table `keywords`
--
ALTER TABLE `keywords`
MODIFY `key_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=236;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `u_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `weekly_report`
--
ALTER TABLE `weekly_report`
MODIFY `wr_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `prods`
--
ALTER TABLE `prods`
ADD CONSTRAINT `prods_ibfk_1` FOREIGN KEY (`prod_user`) REFERENCES `users` (`u_id`);
--
-- Constraints for table `data`
--
ALTER TABLE `data`
ADD CONSTRAINT `data_ibfk_1` FOREIGN KEY (`dat_id`) REFERENCES `keywords` (`key_id`);
--
-- Constraints for table `keywords`
--
ALTER TABLE `keywords`
ADD CONSTRAINT `keywords_ibfk_1` FOREIGN KEY (`key_prod`) REFERENCES `prods` (`prod_id`);
--
-- Constraints for table `weekly_report`
--
ALTER TABLE `weekly_report`
ADD CONSTRAINT `weekly_report_ibfk_1` FOREIGN KEY (`wr_prod_id`) REFERENCES `prods` (`prod_id`);
Can you please tell me if the FOREIGN KEYs have been done right? of should I change something with my structure?
Will "CASCADE" work in this case without any issues?
Thanks a lot.
EDIT:
Is this what's causing all the problems?
ALTER TABLE `keywords`
ADD CONSTRAINT `keywords_ibfk_1` FOREIGN KEY (`key_prod`) REFERENCES `prods` (`prod_id`);
If yes, in this current state, with all the data I currently have on my DB, how can I cancel this and flip it around with no errors?
More information about the current structure:
Every 'prod' has more than 1 keywords ('keywords' table).
Every 'keyword' has more than one 'data' row.
Every 'prod' has only one user.
Every 'prod' has more than one 'prod_data'.
So just for being sure, following this short explanation: http://www.w3schools.com/sql/sql_foreignkey.asp
The 'key_prod' is clearly the FOREIGN KEY in the "keywords" table, and the 'prod_id' is the "PRIMARY KEY" in the "prods" table.
I'm very confused right now.
EDIT #2:
This is an other solution I found, not so sure how to apply this in my code, but anyway:
The simple way would be to disable the foreign key check; make the
changes then re-enable foreign key check.
SET FOREIGN_KEY_CHECKS=0; -- to disable them
SET FOREIGN_KEY_CHECKS=1; -- to re-enable them
I'm not sure if it's a workaround, or a real solution for this kind of problem, and I really want my code to work "by the book" especially when I'm new to working with this kind of stuff.
I had work with similar database project. First backup your database.
Try to drop your foreign key.
ALTER TABLE table_name DROP FOREIGN KEY column_name_ibfk_1;
After that you can now create a foreign key which can do your above mentioned behaviour.
ALTER TABLE table_name ADD FOREIGN KEY(column_name) REFERENCES table_name(column_name) ON DELETE CASCADE ON UPDATE CASCADE;

Change Primary Key from BigInt to Unsigned BigInt when linked as foreign key

I have a scenario like this:
CREATE TABLE `Users` (
`IdUser` bigint(20) NOT NULL PRIMARY KEY
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `MainTable` (
`IdLite` bigint(20) NOT NULL PRIMARY KEY
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `LinkedTable` (
`IdUser` bigint(20) NOT NULL,
`IdLite` bigint(20) NOT NULL,
PRIMARY KEY (`IdUser`, `IdLite`),
FOREIGN KEY (`IdUser`) REFERENCES `Users` (`IdUser`),
FOREIGN KEY (`IdLite`) REFERENCES `MainTable` (`IdLite`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I'm trying to change IdLite to Unsigned with a query like this:
SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE `MainTable` CHANGE `IdLite`
`IdLite` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE `LinkedTable` CHANGE `IdLite`
`IdLite` BIGINT(20) UNSIGNED NOT NULL;
SET FOREIGN_KEY_CHECKS=1;
but I get error:
errno: 150 - Foreign key constraint is incorrectly formed
How can I solve?
You can't change the data type of columns used in an existing FK constraint.
You can drop the FK constraint, change the column data types and then recreate the FK constraint:
ALTER TABLE LinkedTable
DROP FOREIGN KEY linkedtable_ibfk_2; -- or whatever the symbol is named
ALTER TABLE MainTable
MODIFY IdLite SERIAL; -- alias of BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE
ALTER TABLE LinkedTable
MODIFY IdLite BIGINT UNSIGNED NOT NULL,
ADD FOREIGN KEY (IdLite) REFERENCES MainTable (IdLite);

Contraint sql error: #1005 - Can't create table

Error
I have a working site in one server. I decided to move it to another company. I exported the database with phpmyadmin and uploaded in the new server. Everytime I try to import the database I receive this error:
SQL query:
--
-- Constraints for table `seller_cart`
--
ALTER TABLE `seller_cart`
ADD CONSTRAINT `seller_cart_ibfk_1`
FOREIGN KEY ( `subscription` )
REFERENCES `subscription` ( `id` ) ,
ADD CONSTRAINT `seller_cart_ibfk_2`
FOREIGN KEY ( `user` )
REFERENCES `users` ( `user_id` )
ON DELETE CASCADE
ON UPDATE CASCADE ,
ADD CONSTRAINT `seller_cart_ibfk_3`
FOREIGN KEY ( `featured_item` )
REFERENCES `featured_item` ( `item` )
ON DELETE CASCADE
ON UPDATE CASCADE ;
MySQL said: Documentation
#1005 - Can't create table 'project123.#sql-12050_1d' (errno: 150) (Details...)
HERE'S THE STRUCTURE OF seller cart:
--
-- Table structure for table `seller_cart`
--
CREATE TABLE IF NOT EXISTS `seller_cart` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user` bigint(20) NOT NULL,
`subscription` bigint(20) DEFAULT NULL,
`description` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
`item_listings` text COLLATE utf8_unicode_ci,
`featured_item` bigint(20) DEFAULT NULL,
`quantity` int(2) NOT NULL,
`price` float NOT NULL,
PRIMARY KEY (`id`),
KEY `user` (`user`),
KEY `subscription` (`subscription`),
KEY `featured_item` (`featured_item`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
What could be the problem? I just exported and imported the samedatabase. Even tried on a localhost and the same problem.
This error is thrown when you are trying to refer a column which is not indexed.
Check if
subscription ( id )
users ( user_id )
featured_item ( item )
have valid indexes defined. If not, define them and run your ALTER ... statement.
Refer To: Rules for Foreign Key Constraints:
InnoDB and FOREIGN KEY Constraints

MySQL foreign key ON DELETE SET NULL check data types error

I'm working on a normalised database, to be secure I wanted to use foreign keys.
My database:
CREATE TABLE `names` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `name_2` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `name_id` (`name_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The command:
ALTER TABLE `names` ADD FOREIGN KEY ( `name` ) REFERENCES `temp`.`users` (
`name_id`
) ON DELETE SET NULL ON UPDATE CASCADE ;
The response (error):
Error creating foreign key on name (check data types)
So, how to fix this?
The error is self explanatory. Name in names table is of type varchar(250) whereas name_id in users table is of type int(11).
But I believe you meant to have an FK all the way around in users table referencing names table.
ALTER TABLE users
ADD FOREIGN KEY (name_id) REFERENCES names (id)
ON DELETE SET NULL ON UPDATE CASCADE;
Here is SQLFiddle demo
Both keys have to be the same type and length,you have varchar and int.
Here is what you want:
ALTER TABLE `names` ADD FOREIGN KEY ( `id` ) REFERENCES `users` (
`name_id`)

mysql cannot create foreign key

here are my two tables
CREATE TABLE IF NOT EXISTS `carslibrary` (
`CarID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`CarName` varchar(255) NOT NULL,
`colorslibrary_ID` int(11) unsigned NOT NULL,
PRIMARY KEY (`CarID`),
KEY `colorslibrary_ID` (`colorslibrary_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
CREATE TABLE IF NOT EXISTS `colorslibrary` (
`ColorID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`ColorName` varchar(255) NOT NULL,
PRIMARY KEY (`ColorID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
I get an error on the following query:
ALTER TABLE `carslibrary` ADD FOREIGN KEY ( `colorslibrary_ID` )
REFERENCES `cars2`.`colorslibrary` (`ColorID` );
MySQL says:
#1452 - Cannot add or update a child row: a foreign key constraint
fails (`cars2`.<result 2 when explaining filename
'#sql-cf8_41a'>, CONSTRAINT `#sql-cf8_41a_ibfk_1` FOREIGN KEY
(`colorslibrary_ID`) REFERENCES `colorslibrary` (`ColorID`))
Your tables aren't empty, therefore a constraint fails (reference not found) when you create it.
Use SET FOREIGN_KEY_CHECKS = 0; and re-run your alter table.
I would firstly identify orphaned rows in the carslibrary table:
select * from carslibrary where colorslibrary_ID not in (select ColorID from cars2.colorslibrary);
Then decide what you want to do with these orphaned rows. Want to DELETE them from the carslibrary table? UPDATE them to an existing parent ColorID in the colorslibrary? INSERT a new ColorID in the colorslibrary table to cater for the orphaned rows?
Once you've tidied up your data you should be able to run the ALTER TABLE with no errors.