mariaDB foreign key unformed - varchar not a signed/unsigned issue - mysql

MAC Sierra 10.12.2
mariaDB Vers 10.1.19
Construct statements are cut/paste from Querious Table Syntax window.
First table:
CREATE TABLE `USAStates` (
`state_id` int(11) unsigned zerofill NOT NULL AUTO_INCREMENT,
`state_abbrev` varchar(6) NOT NULL DEFAULT '',
`electoral_votes` smallint(2) DEFAULT '0',
`fed_reg` smallint(2) DEFAULT '0',
`econ_anal_reg` varchar(128) DEFAULT NULL,
`FRB_district` varchar(128) DEFAULT NULL,
PRIMARY KEY (`state_id`,`state_abbrev`)
) ENGINE=InnoDB AUTO_INCREMENT=52 DEFAULT CHARSET=utf8;
Second Table:
CREATE TABLE `FRBCommentary` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state_abbrev` varchar(6) NOT NULL DEFAULT '',
`FRB_district_rem` longtext,
PRIMARY KEY (`id`,`state_abbrev`)
) ENGINE=InnoDB AUTO_INCREMENT=52 DEFAULT CHARSET=utf8;
Results of ALTER statement from command window; same results using Querious tools:
MariaDB [ESHOP]>
ALTER TABLE FRBCommentary
ADD CONSTRAINT FOREIGN KEY (state_abbrev)
REFERENCES USAStates (state_abbrev);
ERROR 1005 (HY000): Can't create table eshop.#sql-74b_41 (errno:
150 "Foreign key constraint is incorrectly formed") MariaDB [ESHOP]>
Used to be very competent at MS Access...years later trying to learn the real thing.

You need an index on the referenced column.
ALTER TABLE USAStates ADD INDEX (state_abbrev);

Related

MYSQL, errno: 150 "Foreign key constraint is incorrectly formed"

I need help with this problem in MySQL. I have this table:
CREATE TABLE syncproductscard(
`idsyncproductscard` int(10) unsigned NOT NULL AUTO_INCREMENT,
`idsyncproducts` int(10) NOT NULL,
`carsa` varchar(20) DEFAULT NULL,
`emsa` varchar(20) DEFAULT NULL,
`column` varchar(250) DEFAULT NULL,
`val` varchar(2000) DEFAULT NULL,
`filter` varchar(500) DEFAULT NULL,
`video` varchar(256) DEFAULT NULL,
PRIMARY KEY (`idsyncproductscard`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
but alter table for add foreign key, does not work
ALTER TABLE syncproductscard
ADD CONSTRAINT `fk_idsyncproducts`
FOREIGN KEY (`idsyncproducts`)
REFERENCES syncproducts(`idsyncproducts`)
ON DELETE CASCADE;
MySQL says:
Error Code: 1005. Can't create table AAA.#sql-41d0_60 (errno: 150 "Foreign key constraint is incorrectly formed") 0.016 sec
Inspect the two tables and ensure they have the same properties.
ENGINE = InnoDB
CHARSET = utf8
You should be good to go.

Foreign key constraint is incorrectly formed : MySQL

Session Table is here:
CREATE TABLE `sessions` (
`id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(11) DEFAULT NULL,
`ip_address` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
User Table is below
CREATE TABLE IF NOT EXISTS `tblusers` (
`UserID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`UserName` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`EmailAddress` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`RoleID` tinyint(4) NOT NULL,
PRIMARY KEY (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=17;
I tried below query to apply Foreign Key Constraint in Sessions Table
ALTER TABLE sessions
ADD CONSTRAINT FK_sessions_tblusers_UserID
FOREIGN KEY (user_id)
REFERENCES tblusers(UserID)
MySQL says
1005 - Can't create table myapp.#sql-6b8_83 (errno: 150 "Foreign
key constraint is incorrectly formed")
Question
Am I missing something ?
The issue here is that the column types of sessions.user_id and tblusers.UserID don't quite match. I reproduced the same error and fixed it by altering the two columns as follows...
`user_id` INT(11) UNSIGNED DEFAULT NULL
...and...
`UserID` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT
The foreign key was successfully created after I made those changes. Note that I didn't have to change the nullability to match, though you may want to do this with sessions.user_id if a session is required to have a user id...
`user_id` INT(11) UNSIGNED NOT NULL

Unable to create foreign key constraint in MySQL. Error number 150

I am attempting to create a data model. It's fairly complicated, but I'm trying to link the Splits table to the Trials table. A screenshot of the model is below:
I'm attempting to make Splits.protocol + Splits.resultID + Splits.trialNumber a foreign key to Trials. Those three relations are the primary key of Trials. I'm doing this with MySQL Workbench and it throws an Error #150. Does anyone know what the problem is?
Here is the SQL statement and the error that it throws when attempting to execute it:
ERROR 1005: Can't create table '403898_BAMNormalized.#sql-7285_6c29081' (errno: 150)
SQL Statement:
ALTER TABLE `403898_BAMNormalized`.`Splits`
ADD CONSTRAINT `FK_FromTrial`
FOREIGN KEY (`protocol` , `resultID` , `trialNumber`)
REFERENCES `403898_BAMNormalized`.`Trials` (`protocol` , `resultID` , `trialNumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
ERROR: Error when running failback script. Details follow.
ERROR 1050: Table 'Splits' already exists
SQL Statement:
CREATE TABLE `Splits` (
`protocol` varchar(255) NOT NULL,
`resultID` int(11) NOT NULL,
`trialNumber` int(11) NOT NULL,
`splitNumber` int(11) NOT NULL,
`splitScore` decimal(10,0) NOT NULL,
PRIMARY KEY (`protocol`,`resultID`,`trialNumber`,`splitNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Here are the create table statements:
CREATE TABLE `Trials` (
`resultID` int(11) NOT NULL,
`protocol` varchar(255) NOT NULL,
`trialNumber` int(11) NOT NULL,
`trialScore` decimal(10,0) NOT NULL,
`best` char(1) DEFAULT NULL,
`DQFlag` varchar(45) DEFAULT NULL,
PRIMARY KEY (`resultID`,`protocol`,`trialNumber`),
CONSTRAINT `FK_trialID` FOREIGN KEY (`resultID`, `protocol`) REFERENCES `ResultsDetails` (`resultID`, `protocol`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `Splits` (
`protocol` varchar(255) NOT NULL,
`resultID` int(11) NOT NULL,
`trialNumber` int(11) NOT NULL,
`splitNumber` int(11) NOT NULL,
`splitScore` decimal(10,0) NOT NULL,
PRIMARY KEY (`protocol`,`resultID`,`trialNumber`,`splitNumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Indexes of Trials table:
Reordering the index to represent the same order as the foreign key was the solution. See comments appended to original post for detailed information.

#1215 - Cannot add foreign key constraint

I have this weird issue with creation of foreign key.
Given 2 tables:
CREATE TABLE IF NOT EXISTS `groupdeals` (
`groupdeals_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`product_id` int(10) NOT NULL,
`merchant_id` int(11) NOT NULL,
`minimum_qty` int(11) NOT NULL,
`maximum_qty` int(11) NOT NULL,
`target_met_email` int(11) NOT NULL,
`coupon_barcode` text NOT NULL,
`coupon_merchant_address` int(11) NOT NULL,
`coupon_merchant_contact` int(11) NOT NULL,
`coupon_expiration_date` date DEFAULT NULL,
`coupon_price` int(11) NOT NULL,
`coupon_fine_print` int(11) NOT NULL,
`coupon_highlights` int(11) NOT NULL,
`coupon_merchant_description` int(11) NOT NULL,
`coupon_business_hours` int(11) NOT NULL,
`coupon_merchant_logo` int(11) NOT NULL,
`coupon_additional_info` text NOT NULL,
`position` int(11) NOT NULL,
PRIMARY KEY (`groupdeals_id`),
KEY `groupdeals_id` (`groupdeals_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and
CREATE TABLE IF NOT EXISTS `groupdeals_coupons` (
`coupon_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`groupdeals_id` int(11) NOT NULL,
`order_item_id` int(11) NOT NULL,
`coupon_code` varchar(255) NOT NULL DEFAULT '',
`redeem` varchar(255) NOT NULL DEFAULT '',
`status` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`coupon_id`),
KEY `fk_groupdeals_coupons_groupdeals1_idx` (`groupdeals_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I try to add foreign key by executing following query:
ALTER TABLE `groupdeals_coupons`
ADD CONSTRAINT `fk_groupdeals_coupons_groupdeals1`
FOREIGN KEY (`groupdeals_id`)
REFERENCES `groupdeals` (`groupdeals_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
All I receive is Error:
#1215 - Cannot add foreign key constraint
Show engine innodb status
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2013-08-17 13:47:49 7ff5dbb2c700 Error in foreign key constraint of table xxxxx/#sql-7b23_282b1a:
FOREIGN KEY (`groupdeals_id`)
REFERENCES `groupdeals` (`groupdeals_id`)
ON DELETE CASCADE
ON UPDATE CASCADE:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
The column groupdeals.groupdeals_id is a primary one, so I really can't understand where is a problem :|
Any hints?
Server type: Percona Server
Server version: 5.6.11-rc60.3-log - Percona Server (GPL), Release 60.3
Your types are inconsistent:
CREATE TABLE IF NOT EXISTS `groupdeals` (
`groupdeals_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
CREATE TABLE IF NOT EXISTS `groupdeals_coupons` (
[...]
`groupdeals_id` int(11) NOT NULL,
As you will see, in one table you have int unsigned. In the other, just int.
BTW, I noticed you have two keys on groupdeals_id. Is that on purpose?
CREATE TABLE IF NOT EXISTS `groupdeals` (
[...]
PRIMARY KEY (`groupdeals_id`),
KEY `groupdeals_id` (`groupdeals_id`)
Try these two steps to add foreign key:-
alter table groupdeals_coupons modify groupdeals_id int unsigned not null default 0;
ALTER TABLE groupdeals_coupons ADD CONSTRAINT fk_groupdeals_coupons_groupdeals1 FOREIGN KEY (groupdeals_id) references groupdeals (roupdeals_id);

MySQL: Error Message Can't create table (errno: 150)

I have two tables, 'po' and 'receive'
CREATE TABLE `po` (
`PO_ID` bigint(20) NOT NULL,
`SERVICE_TYPE` bit(1) DEFAULT NULL,
`ENTRY_DATE` date NOT NULL,
`RECEIPT_DATE` date DEFAULT NULL,
`TURNOVER` date DEFAULT NULL,
`MOBILIZATION` date DEFAULT NULL,
`SITE_NAME` varchar(255) NOT NULL,
`SITE_CODE` varchar(45) DEFAULT NULL,
`SITE_TIN` varchar(45) DEFAULT NULL,
`SITE_ADDRESS` varchar(255) NOT NULL,
`COST` decimal(11,2) NOT NULL,
`XML` text,
PRIMARY KEY (`PO_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
CREATE TABLE `receive` (
`RECEIPT_ID` varchar(100) NOT NULL,
`RECEIPT_DATE` date NOT NULL,
`PO_NUMBER` bigint(20) NOT NULL,
`SUPPLIER_ID` int(11) NOT NULL,
PRIMARY KEY (`RECEIPT_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
I'm trying to connect two tables by defining a foreign key 'fk_po' on the table 'receive'
ALTER TABLE `fourthwave`.`receive`
ADD CONSTRAINT `fk_po`
FOREIGN KEY (`PO_NUMBER` )
REFERENCES `fourthwave`.`po` (`PO_ID` )
ON DELETE SET NULL
ON UPDATE SET NULL
, ADD INDEX `fk_po` (`PO_NUMBER` ASC)
However, the alter query above throws an error :
Error Code: 1005. Can't create table 'fourthwave.#sql-aec_11' (errno:150)
Am i getting this error because the field's names, 'PO_ID' and 'PO_NUMBER' on both tables are different?
Execute SHOW ENGINE INNODB STATUS statement after ALTER TABLE, and you will see the error message - 'You have defined a SET NULL condition though some of the
columns are defined as NOT NULL'.
ALTER TABLE `receive`
ADD CONSTRAINT `fk_po`
FOREIGN KEY (`PO_NUMBER` )
REFERENCES `po` (`PO_ID` )
ON DELETE SET NULL
ON UPDATE SET NULL
, ADD INDEX `fk_po` (`PO_NUMBER` ASC);
SHOW ENGINE INNODB STATUS;
You need an index on PO_NUMBER in the receive table. The field you are referencing in a foreign key always should be indexed.