Foreign key referring to primary key in the same table Mysql - mysql

# Sql to create userdetails table:
CREATE TABLE `userdetails` (
`user_details_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
`user_group_id` int(1) unsigned NOT NULL,
`name` varchar(50) NOT NULL,
`email_id` varchar(50),
`password` varchar(50) NOT NULL,
`mobile_no` varchar(10) NOT NULL,
`company_id` int(3) unsigned,
`vehicle_id` varchar(10),
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_updated` datetime NOT NULL,
`created_by` int(3) unsigned NOT NULL,
`status` enum('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (`user_details_id`),
UNIQUE KEY `email_id` (`email_id`),
FOREIGN KEY (`user_group_id`) REFERENCES `usergroups` (`user_group_id`),
FOREIGN KEY (`company_id`) REFERENCES `companies` (`company_id`),
FOREIGN KEY (`created_by`) REFERENCES `userdetails` (`user_details_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Focusing on the 'user_details_id' and 'created_by' columns, the conflict arises when created_by is not referring to an existing user_details_id.
Meaning, if I am creating my own profile with the required details, my user_details_id has not been generated yet and hence I do not know what value to input into the created_by field (which is ideally supposed to contain my user_details_id).
I would appreciate if anyone can guide me in the right direction on how to approach such a conflict, and if there is a way to determine what the value of the user_details_id field could be before it's even generated.
Thanks.

You can't handle it by temporarily disabling foreign key checks by setting server variable foreign_key_checks
SET FOREIGN_KEY_CHECKS=0;
INSERT INTO cities userdetails(....);
SET FOREIGN_KEY_CHECKS = 1;

# Sql to create userdetails table:
CREATE TABLE `userdetails` (
`user_details_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
`user_group_id` int(1) unsigned NOT NULL,
`name` varchar(50) NOT NULL,
`email_id` varchar(50),
`password` varchar(50) NOT NULL,
`mobile_no` varchar(10) NOT NULL,
`company_id` int(3) unsigned,
`vehicle_id` varchar(10),
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_updated` datetime NOT NULL,
`created_by` int(3) unsigned,
`status` enum('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (`user_details_id`),
UNIQUE KEY `email_id` (`email_id`),
FOREIGN KEY (`user_group_id`) REFERENCES `usergroups` (`user_group_id`),
FOREIGN KEY (`company_id`) REFERENCES `companies` (`company_id`),
FOREIGN KEY (`created_by`) REFERENCES `userdetails` (`user_details_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Allowing created_by to accept NULL values seems to be a quick fix to this problem as that can imply user is self-created.

Related

Alter table foreign key constraint fails

When I try to do this:
ALTER TABLE credit_card ADD CONSTRAINT fk_company FOREIGN KEY (company_id) REFERENCES company (id);
I got the error a foreign key constraint fails, but I don't understand why. The company_id column has same type of company.id column as you can see:
Company table
CREATE TABLE `company` (
`id` bigint NOT NULL AUTO_INCREMENT,
`code` varchar(10) NOT NULL,
`description` varchar(50) NOT NULL,
`currency_id` bigint NOT NULL,
`language_id` bigint DEFAULT NULL,
`address_id` bigint DEFAULT NULL,
`creation_time` datetime NOT NULL,
`modification_time` datetime DEFAULT NULL,
`deleted` tinyint(1) NOT NULL DEFAULT '0',
`cost_center_modifiable` tinyint(1) DEFAULT NULL,
`use_colleague_cost_center` tinyint(1) DEFAULT NULL,
`fixed_guest_company` varchar(50) DEFAULT NULL,
`info_number` int DEFAULT NULL,
`use_kilometric_rate` tinyint(1) DEFAULT NULL,
`use_multiple_km_rate` tinyint(1) DEFAULT NULL,
`email_required` tinyint(1) DEFAULT NULL,
`logo` varchar(255) DEFAULT NULL,
`holding_id` bigint NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`),
KEY `fk_company_address1` (`address_id`),
KEY `fk_company_currency1` (`currency_id`),
KEY `company_language_FK` (`language_id`),
KEY `company_holding_FK` (`holding_id`),
CONSTRAINT `company_currency_FK` FOREIGN KEY (`currency_id`) REFERENCES `currency` (`id`),
CONSTRAINT `company_holding_FK` FOREIGN KEY (`holding_id`) REFERENCES `holding` (`id`),
CONSTRAINT `company_language_FK` FOREIGN KEY (`language_id`) REFERENCES `language` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=142 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
Credit_card table
CREATE TABLE `credit_card` (
`id` bigint NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`pan` varchar(16) NOT NULL,
`account` varchar(50) DEFAULT NULL,
`begin_date` date NOT NULL,
`end_date` date NOT NULL,
`disabled` tinyint(1) NOT NULL DEFAULT '0',
`creation_time` datetime NOT NULL,
`modification_time` datetime DEFAULT NULL,
`company_id` bigint NOT NULL,
PRIMARY KEY (`id`),
KEY `username` (`username`),
KEY `pan` (`pan`),
CONSTRAINT `fk_credit_card_user_ext` FOREIGN KEY (`username`) REFERENCES `users_extension` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8mb3
Dont make auto increment columns as foreign keys or unless not sure, dont reference these to autoincrement columns as it may end up making the table with foreign key issue a constraint violation if redundant entries are expected to be made in either of the tables.
Might be the case the related data is already ingested and then the table is altered

MySQL "Foreign key constraint is incorrectly formed"

I have the follwing SQL commands:
CREATE TABLE IF NOT EXISTS `users`
(
`id` INTEGER NOT NULL auto_increment,
`username` VARCHAR(255) NOT NULL UNIQUE,
`password` VARCHAR(255) NOT NULL,
`root` TINYINT(1) DEFAULT 0,
`createdat` DATETIME NOT NULL,
`updatedat` DATETIME NOT NULL,
UNIQUE `username_unique` (`username`),
PRIMARY KEY (`id`)
)
engine=innodb;
CREATE TABLE IF NOT EXISTS `domains`
(
`id` INTEGER NOT NULL auto_increment,
`domain` VARCHAR(255) NOT NULL UNIQUE,
`createdat` DATETIME NOT NULL,
`updatedat` DATETIME NOT NULL,
`userid` INTEGER,
UNIQUE `domain_unique` (`domain`),
PRIMARY KEY (`id`),
FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE SET NULL ON
UPDATE CASCADE
)
engine=innodb;
CREATE TABLE IF NOT EXISTS `aliases`
(
`id` INTEGER NOT NULL auto_increment,
`source_username` VARCHAR(255) NOT NULL,
`source_domain` VARCHAR(255) NOT NULL,
`destination_username` VARCHAR(255) NOT NULL,
`destination_domain` VARCHAR(255) NOT NULL,
`enabled` TINYINT(1) NOT NULL DEFAULT 1,
`createdat` DATETIME NOT NULL,
`updatedat` DATETIME NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`source_domain`) REFERENCES `domains` (`domain`)
)
engine=innodb;
CREATE TABLE IF NOT EXISTS `accounts`
(
`id` INTEGER NOT NULL auto_increment,
`username` VARCHAR(255) NOT NULL,
`domain` VARCHAR(255) NOT NULL,
`password` VARCHAR(255) NOT NULL,
`quota` INTEGER NOT NULL DEFAULT 500,
`enabled` TINYINT(1) NOT NULL DEFAULT 1,
`sendonly` TINYINT(1) NOT NULL DEFAULT 0,
`createdat` DATETIME NOT NULL,
`updatedat` DATETIME NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`domain`) REFERENCES `domains` (`domain`)
)
engine=innodb;
if i try to run these i get the message:
"Foreign key constraint is incorrectly formed"
for the tables Alias and Accounts.
Its not possible to use primary keys in alias and accounts
Im using MariaDB 10.2
I hope somebody can tell me what is wrong with these statements.
You need to add a key/index to the domain field of the domains table, in order for it to be used as Foreign Key by another table.
If the table is already created and you want to add an index, use this.
CREATE INDEX domain ON domains(domain);
OR add the index while creating the table -
CREATE TABLE IF NOT EXISTS `domains`
(
`id` INTEGER NOT NULL auto_increment,
`domain` VARCHAR(255) NOT NULL UNIQUE,
`createdat` DATETIME NOT NULL,
`updatedat` DATETIME NOT NULL,
`userid` INTEGER,
UNIQUE `domain_unique` (`domain`),
PRIMARY KEY (`id`),
INDEX domain (domain),
FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE SET NULL ON
UPDATE CASCADE
)
engine=innodb;
For further reading (official documentation) regarding Foreign Key Contraint Errors on MariaDB this URL
You define an integer primary key. Use it:
CREATE TABLE IF NOT EXISTS `aliases`
(
`id` INTEGER NOT NULL auto_increment,
`source_username` VARCHAR(255) NOT NULL,
`source_domain_id` INTEGER NOT NULL,
`destination_username` VARCHAR(255) NOT NULL,
`destination_domain` VARCHAR(255) NOT NULL,
`enabled` TINYINT(1) NOT NULL DEFAULT 1,
`createdat` DATETIME NOT NULL,
`updatedat` DATETIME NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`source_domain_id`) REFERENCES `domains` (`id`)
)
engine=innodb;

Best normalised practice to map phone numbers with user or office

I am designing a DB in MySQL. I have a user table, office table and a phone number table as I intend to allow multiple phone numbers to a user or for an office. so I know I need to add foreign keys in phone number table to office table and to user table rather than the other way round. But how do I do it without a null record?
What is the best-normalized way to make this with neither officeId not userId in the phone number record null?
MY Phone number table
CREATE TABLE `phonenumber` (
`Id` varchar(36) NOT NULL,
`Title` varchar(100) DEFAULT NULL,
`UserId` varchar(36) DEFAULT NULL,
`SchoolId` int(11) DEFAULT NULL,
`CreatedOn` datetime NOT NULL,
`ModifiedOn` datetime NOT NULL,
`CreatedBy` varchar(36) NOT NULL,
`ModifiedBy` varchar(36) NOT NULL,
`Number` varchar(20) NOT NULL,
PRIMARY KEY (`Id`),
KEY `FK_Phone_User` (`UserId`),
KEY `FK_Phone_School` (`SchoolId`),
CONSTRAINT `FK_Phone_School` FOREIGN KEY (`SchoolId`) REFERENCES `school` (`Id`),
CONSTRAINT `FK_Phone_User` FOREIGN KEY (`UserId`) REFERENCES `user` (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
My User Table
CREATE TABLE `user` (
`Id` varchar(36) NOT NULL,
`UserName` varchar(20) NOT NULL,
`DisplayName` varchar(100) DEFAULT NULL,
`OfficialName` varchar(100) DEFAULT NULL,
`PasswordHash` varchar(50) DEFAULT NULL,
`CreatedOn` datetime DEFAULT NULL,
`CreatedBy` varchar(36) DEFAULT NULL,
`ModifiedOn` datetime DEFAULT NULL,
`ModifiedBy` varchar(36) DEFAULT NULL,
PRIMARY KEY (`Id`),
UNIQUE KEY `UserName` (`UserName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
My School table
CREATE TABLE `school` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(100) NOT NULL,
`AddressId` varchar(36) DEFAULT NULL,
`CreatedOn` datetime NOT NULL,
`ModifiedOn` datetime NOT NULL,
`CreatedBy` varchar(36) NOT NULL,
`ModifiedBy` varchar(36) NOT NULL,
PRIMARY KEY (`Id`),
KEY `FK_School_Address` (`AddressId`),
CONSTRAINT `FK_School_Address` FOREIGN KEY (`AddressId`) REFERENCES `address` (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You simply have to allow for NULL fields during the creation of the Phone_numbers table. What you were warned against is having a whole record with NULLs. You are correctly handling the field that but not saying anything or saying NULL. Here's an example:
CREATE TABLE Phone_numbers(
phone_number VARCHAR(15) NOT NULL,
user_id INT UNSIGNED,
office_id INT UNSIGNED,
PRIMARY KEY (phone_number),
CONSTRAINT RefUsers1 FOREIGN KEY (user_id)
REFERENCES Users(user_id),
CONSTRAINT RefOffices2 FOREIGN KEY (office_id)
REFERENCES Offices(office_id)
)ENGINE=INNODB
;
For this simple model

#1005 - Can't create table errno: 150 Magento

I am trying to create a new table for magento and I am trying to reference existing magento tables. From what I googled, the problem that I am getting can be 1 of the 2 issues.
The FK must have a index
The PK must exist before the FK can reference
In both cases, I believe I did both of these correctly. Below is existing table schemas
ALREADY EXISTING TABLES BEING REFERENCED
CREATE TABLE IF NOT EXISTS `core_store` (
`store_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(32) NOT NULL DEFAULT '',
`website_id` smallint(5) unsigned DEFAULT '0',
`group_id` smallint(5) unsigned NOT NULL DEFAULT '0',
`name` varchar(255) NOT NULL,
`sort_order` smallint(5) unsigned NOT NULL DEFAULT '0',
`is_active` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`store_id`),
UNIQUE KEY `code` (`code`),
KEY `FK_STORE_WEBSITE` (`website_id`),
KEY `is_active` (`is_active`,`sort_order`),
KEY `FK_STORE_GROUP` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Stores' AUTO_INCREMENT=9 ;
CREATE TABLE IF NOT EXISTS `admin_user` (
`user_id` mediumint(9) unsigned NOT NULL AUTO_INCREMENT,
`firstname` varchar(32) NOT NULL DEFAULT '',
`lastname` varchar(32) NOT NULL DEFAULT '',
`email` varchar(128) NOT NULL DEFAULT '',
`username` varchar(40) NOT NULL DEFAULT '',
`password` varchar(100) NOT NULL DEFAULT '',
`created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`modified` datetime DEFAULT NULL,
`logdate` datetime DEFAULT NULL,
`lognum` smallint(5) unsigned NOT NULL DEFAULT '0',
`reload_acl_flag` tinyint(1) NOT NULL DEFAULT '0',
`is_active` tinyint(1) NOT NULL DEFAULT '1',
`extra` text,
`failures_num` smallint(6) NOT NULL DEFAULT '0',
`first_failure` datetime DEFAULT NULL,
`lock_expires` datetime DEFAULT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `UNQ_ADMIN_USER_USERNAME` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Users' AUTO_INCREMENT=25 ;
Table I am trying to create
CREATE TABLE `oro_dashboard`
( `id` int unsigned NOT NULL,
`name` varchar(255) NOT NULL default '',
`description` varchar(64) NOT NULL default '',
`created_by` int unsigned NOT NULL default '0',
`created_at` date,
`layout` varchar(255) NOT NULL default '',
`default_store_id` int,
PRIMARY KEY (`id`),
KEY `IDX_ORO_DASHBOARD_CREATED_BY` (`created_by`),
CONSTRAINT `FK_ORO_DASHBOARD_CREATED_BY_ADMIN_USER_USER_ID` FOREIGN KEY (`created_by`) REFERENCES `admin_user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_ORO_DASHBOARD_DEFAULT_STORE_ID_CORE_STORE_STORE_ID` FOREIGN KEY (`default_store_id`) REFERENCES `core_store` (`store_id`) ON DELETE SET NULL ON UPDATE CASCADE )
ENGINE=INNODB charset=utf8 COLLATE=utf8_unicode_ci
In magento, I found there is in deed a table called admin_user that does have a column called user_id. There is a core_store table that does have a column called store_id. and both my columns have INDEXES made.
Does anyone have any clue what the issue maybe ? Below is my error message
#1005 - Can't create table 'db.oro_dashboard' (errno: 150)
It is necessary to have data type to be same for the foreign key and its corresponding parent key. The data type is different of the foreign key and its referencing parent key in your table that is why it is giving an error.
created by is int unsigned while userid is medium int in parent table
same is problem in the second foreign key
reference http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
When defining foreign keys, the data type must be the same.
You are defining core_store.store_id as smallint(5) unsigned and so the referencing column must be the same: oro_dashboard.default_store_id.
Do also with oro_dashboard.created_by
Final oro_dashboard CREATE TABLE query,
CREATE TABLE `oro_dashboard`
( `id` int unsigned NOT NULL,
`name` varchar(255) NOT NULL default '',
`description` varchar(64) NOT NULL default '',
`created_by` mediumint(9) unsigned NOT NULL default '0',
`created_at` date,
`layout` varchar(255) NOT NULL default '',
`default_store_id` smallint(5) unsigned,
PRIMARY KEY (`id`),
KEY `IDX_ORO_DASHBOARD_CREATED_BY` (`created_by`) ,
CONSTRAINT `FK_ORO_DASHBOARD_CREATED_BY_ADMIN_USER_USER_ID`
FOREIGN KEY (`created_by`)
REFERENCES `admin_user` (`user_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_ORO_DASHBOARD_DEFAULT_STORE_ID_CORE_STORE_STORE_ID`
FOREIGN KEY (`default_store_id`)
REFERENCES `core_store` (`store_id`)
ON DELETE SET NULL ON UPDATE CASCADE
)
SQLFIddle Demo
It appears that the column definition for default_store_id does not match core_store.store_id. it should be smallint(5) unsigned in your table. created_by has the same problem, although it did not prevent the table from being created

cannot add second FK : got error can't create table'.jobstatus\#sql-32c_12f2f.frm' (errno:150)

CREATE TABLE `job` (
`jobId` int(11) NOT NULL auto_increment,
`jobcode` varchar(25) default NULL,
`jobname` varchar(255) default NULL,
`location` varchar(255) default NULL,
`budget` int(10) unsigned default NULL,
`year_type` varchar(100) default NULL,
`worklineId` int(11) default NULL,
PRIMARY KEY (`jobId`),
KEY `NewIndex` (`worklineId`),
FOREIGN KEY (`worklineId`) REFERENCES `workline` (`worklineId`)
) TYPE=InnoDB;
CREATE TABLE `subjob` (
`subjobId` int(11) NOT NULL auto_increment,
`subjobcode` varchar(25) default NULL,
`subjobname` varchar(255) default NULL,
`subjobbudget` int(11) unsigned default NULL,
`jobgoal_date` date default '0000-00-00',
`jobId` int(11) default NULL,
PRIMARY KEY (`subjobId`),
KEY `NewIndex` (`jobId`),
FOREIGN KEY (`jobId`) REFERENCES `job` (`jobId`)
) TYPE=InnoDB;
CREATE TABLE `contract` (
`contractId` int(11) NOT NULL auto_increment,
`contractcode` varchar(25) default NULL,
`price` int(11) unsigned default NULL,
`contractprice` int(11) unsigned default NULL,
`company` varchar(50) default NULL,
`signdate` date default '0000-00-00',
`begindate` date default '0000-00-00',
`enddateplan` date default '0000-00-00',
`note` text,
PRIMARY KEY (`contractId`)
) TYPE=InnoDB;
CREATE TABLE `subjob_contract` (
`subjobcontractId` int(11) NOT NULL auto_increment,
`status` varchar(11) default NULL,
`contractId` int(11) default NULL,
`subjobId` int(11) default NULL,
PRIMARY KEY (`subjobcontractId`),
KEY `NewIndex` (`contractId`),
KEY `NewIndex2` (`subjobId`),
FOREIGN KEY (`contractId`) REFERENCES `contract` (`contractId`)
) TYPE=InnoDB
I m using mysql front 3.2 to manage database,I can add first fk but when i add second fk i got an error following this :
sql execution error #1005. response from the database: can't create table'.jobstatus#sql-32c_12f2f.frm' (errno:150). i already define the new index for fk subjobId reference to subjob table what could be the possibility of this error? thank you
Check the datatype and size of the subjobId column on primary table and referenced table. both must be same than it will allow you to create foreign key.
Answer is: You can not refer that column/table which is not created yet. Try to execute tables having foreign keys after the referenced tables.
Obviously you should have consistency in datatypes of foreign key and referenced column as well
Correct Execution Demo. Also You should use Engine=InnoDB instead of Type=InnoDB