Create a relationship between the tables when the table is first created - mysql

I use mysql
in my database
I want to create multiple tables with delete and update relationship
as an example
I want to link the profiles table to the users table
Associate the mm_id_user column from the users table with the mm_id_profile column from the profiles table
What I actually tried to do is this example and it didn't work for me
https://stackoverflow.com/a/260453/10206991
https://stackoverflow.com/a/9796950/10206991
The code used to create the users table and it succeeds in creating the table
CREATE TABLE users (
mm_email VARCHAR(255) NOT NULL,
mm_id_user int NOT NULL AUTO_INCREMENT,
mm_name VARCHAR(25) NOT NULL,
mm_password VARCHAR(255) NOT NULL,
mm_code_reset_pass VARCHAR(100) NOT NULL,
mm_code_check_email VARCHAR(100) NOT NULL,
mm_status CHAR(1) NOT NULL DEFAULT '0',
mm_date_create_account TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
mm_date_last_login TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
mm_is_login CHAR(1) NOT NULL DEFAULT '0',
PRIMARY KEY (mm_id_user, mm_email)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 DEFAULT COLLATE utf8_unicode_ci;
The code used to create the profiles table. He failed to create the table
CREATE TABLE profiles (
mm_id_profile VARCHAR(255) NOT NULL,
mm_image_user TEXT NOT NULL,
mm_num_stores_all VARCHAR(4) NOT NULL,
mm_num_stores_exist VARCHAR(4) NOT NULL,
mm_name_public VARCHAR(25) NOT NULL,
mm_email_public VARCHAR(255) NOT NULL,
mm_phone_public VARCHAR(20) NOT NULL,
mm_location_public TEXT NOT NULL,
mm_update_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX index_profiles(mm_name_public, mm_email_public),
PRIMARY KEY (mm_id_profile),
FOREIGN KEY (mm_id_profile) REFERENCES users(mm_email) ON DELETE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8 DEFAULT COLLATE utf8_unicode_ci;
But if you remove the following line from the profiles table, it will be created
But there is definitely no relationship between the two tables
FOREIGN KEY (mm_id_profile) REFERENCES users(mm_email) ON DELETE CASCADE
This is the error message that appears when creating a profiles table
#1005 - Can't create table `mustforu_test`.`profiles` (errno: 150 "Foreign key constraint is incorrectly formed") (Details…)

There's no reason to put both mm_id_user and mm_email in the primary key of users. If you want emails to be unique, it should have its own unique index. Your current primary key would allow duplicate emails with different IDs.
CREATE TABLE users (
mm_email VARCHAR(255) NOT NULL,
mm_id_user int NOT NULL AUTO_INCREMENT,
mm_name VARCHAR(25) NOT NULL,
mm_password VARCHAR(255) NOT NULL,
mm_code_reset_pass VARCHAR(100) NOT NULL,
mm_code_check_email VARCHAR(100) NOT NULL,
mm_status CHAR(1) NOT NULL DEFAULT '0',
mm_date_create_account TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
mm_date_last_login TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
mm_is_login CHAR(1) NOT NULL DEFAULT '0',
PRIMARY KEY (mm_id_user),
UNIQUE KEY (mm_email)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 DEFAULT COLLATE utf8_unicode_ci;
Giving mm_email its own index will allow the foreign key in profiles to work.

Related

Getting cannot find an index in the referenced table error

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.
Above is the full description of error im getting. i checked the indexes of both table and should be fine but it still gives me this error.
Below is the tables structure.
CREATE TABLE `contact_address` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`address_type` int(5) DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`postcode` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`area` int(5) DEFAULT NULL,
`state` int(5) DEFAULT NULL,
`country` char(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`phone` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`fax` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`contact_branch_id` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` int(4) DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`updated_by` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_c_a_area` (`area`),
KEY `fk_c_a_state` (`state`),
KEY `fk_c_a_country` (`country`),
KEY `fk_c_a_contact_branch_id` (`contact_branch_id`),
KEY `fk_c_a_created_by` (`created_by`),
CONSTRAINT `fk_c_a_area` FOREIGN KEY (`area`) REFERENCES `ref_area` (`area_id`),
CONSTRAINT `fk_c_a_contact_branch_id` FOREIGN KEY (`contact_branch_id`) REFERENCES `contact_branch` (`id`),
CONSTRAINT `fk_c_a_created_by` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`),
CONSTRAINT `fk_c_a_state` FOREIGN KEY (`state`) REFERENCES `ref_state` (`state_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `ref_countries` (
`country_code` char(2) NOT NULL,
`country_id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(80) NOT NULL,
`alpha_3` char(3) DEFAULT NULL,
`calling_code` int(5) NOT NULL,
`continent_name` varchar(30) DEFAULT NULL,
PRIMARY KEY (`country_code`),
KEY `country_id` (`country_id`)
) ENGINE=InnoDB AUTO_INCREMENT=253 DEFAULT CHARSET=utf8mb4;
Im trying to run this and giving me the error.
ALTER TABLE `contact_address`
ADD CONSTRAINT `fk_c_a_countries` FOREIGN KEY (`country`)
REFERENCES `ref_countries` (`country_code`);
The error message you're getting suggests that there's a problem with the foreign key constraint that you're trying to add to the contact_address table. Based on the table definitions you've provided, there are a couple of things that could be causing the issue:
The data type of the country column in the contact_address table is char(2), while the data type of the country_code column in the ref_countries table is char(2) NOT NULL. The NOT NULL constraint on the country_code column may be causing the problem.
Another possibility is that the ref_countries table have not have AUTO_INCREMENT on country_code column, but the contact_address table's country column is referencing that.
You can try the following:
Remove the NOT NULL constraint from the country_code column in the ref_countries table.
Add AUTO_INCREMENT to the country_code column in the ref_countries table.
Also, make sure that there is a matching value in the ref_countries table for each value of the country column in the contact_address table.

Foreign key constraint fails during `drop table`

I have a strange problem in which I'm not able to delete a table as a foreign key constraint fails. The scenario is as follows.
I'm trying to drop the table departments from my DB, the structure for which is as follows:
show create table `departments`
CREATE TABLE `departments` (
`dept_id` int(11) NOT NULL AUTO_INCREMENT,
`dept_name` varchar(50) NOT NULL,
PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Now, the only other table in the database that has department_id is the employee table:
show create table employee
CREATE TABLE `employee` (
`emp_id` varchar(20) NOT NULL,
`role` varchar(10) DEFAULT NULL,
`password` varchar(500) DEFAULT NULL,
`division_id` int(20) DEFAULT NULL,
`email_bb` varchar(100) DEFAULT NULL,
`is_active` tinyint(1) NOT NULL,
`date_joining` date DEFAULT NULL,
`date_confirmation` date DEFAULT NULL,
`date_appraisal` date DEFAULT NULL,
`date_leaving` date DEFAULT NULL,
`first_name` varchar(100) DEFAULT NULL,
`middle_name` varchar(100) DEFAULT NULL,
`last_name` varchar(100) DEFAULT NULL,
`sex` varchar(1) DEFAULT NULL,
`dob` date DEFAULT NULL,
`email_other` varchar(100) DEFAULT NULL,
`contact` varchar(100) DEFAULT NULL,
`present_addr` varchar(1000) DEFAULT NULL,
`perma_addr` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
As you can see, none of these tables are related via foreign keys. So why do I get this error when trying to drop the department table:
#1217 - Cannot delete or update a parent row: a foreign key constraint fails
Is there a better way (and hopefully, simpler) way to see the foreign keys defined? What might be going wrong?
show create table doesn't show incoming FK restraints (e.g. FK is specified in child table, not parent)
So there is a possibility that you have another table with a FK constraint to that table. I usually dump the schema of the database, which shows all FK constraints.

MySQL Error Number 150 when creating Table with Foreign Key

I am having an issue creating a new table in my database. I've seen that the error code it is returning is to do with Foreign Key constraints.
I checked to ensure that the data type of the foreign key in the new table matched the data type of the primary key in the other table. They are both int(11).
However I am still getting an error. Am I missing something? This is my SQL script for creating the new table:
CREATE TABLE `regular_features` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(200) DEFAULT NULL,
`day` VARCHAR(200) DEFAULT NULL,
`description` TEXT DEFAULT NULL,
`programme_id` INT(11) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`programme_id`) REFERENCES directoryprogramme(id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
This is the original table containing the primary key:
CREATE TABLE `directoryprogramme` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(250) NOT NULL,
`broadcast_time` VARCHAR(100) NOT NULL,
`description` TEXT NOT NULL,
`days` VARCHAR(150) NOT NULL,
`contributors` VARCHAR(250) NOT NULL,
`directorycompany_id` INT(11) NOT NULL,
`directorycontact_id` VARCHAR(250) NOT NULL,
`facebook_link` VARCHAR(250) DEFAULT NULL,
`twitter_link` VARCHAR(250) DEFAULT NULL,
`wikipedia_link` VARCHAR(250) DEFAULT NULL,
`web` VARCHAR(250) DEFAULT NULL,
`imageextension` VARCHAR(10) DEFAULT NULL,
`type` VARCHAR(20) NOT NULL DEFAULT 'other',
PRIMARY KEY (`id`)
) ENGINE=MYISAM AUTO_INCREMENT=1161 DEFAULT CHARSET=utf8;
The Foreign Key will be the id of directoryprogramme
The problem is the last line of your create statement:
ENGINE=INNODB DEFAULT CHARSET=utf8;
You mix MYISAM in ald table with INNODB in your new table.
That doesn't work.
Chnage the engine in your new table to MYISAM and it works.

mysql add foreign key constraint error

I have two tables which I'd like to connect with foreign key constraint
For some reason, when I try to do it, it fails and and says: #1215 - Cannot add foreign key constraint
Here is my first table:
CREATE TABLE `zmaneyhayom` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`zman_id` varchar(255) NOT NULL,
`tempHour` tinyint(1) NOT NULL,
`tempHourType` varchar(255) NOT NULL,
`tempHourNum` double NOT NULL,
`tempMinutes` tinyint(1) NOT NULL,
`tempMinutesType` varchar(255) NOT NULL,
`tempMinutesNum` double NOT NULL,
`regularMinutes` tinyint(1) NOT NULL,
`regularMinutesNum` double NOT NULL,
`equivalentMinutes` tinyint(1) NOT NULL,
`equivalentMinutesNum` double NOT NULL,
`degreesBelowHorizon` tinyint(1) NOT NULL,
`degreesBelowHorizonNum` double NOT NULL,
`beforeAfter` varchar(6) NOT NULL,
`riseSet` varchar(4) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zman_id_2` (`zman_id`),
KEY `zman_id` (`zman_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
And this table holds ID and name, which eventually the ID in this table is the name for the previous table (zman_id column):
CREATE TABLE `zmaneyhayomlabels` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
This is the code I'm attempting in order to create the constraint:
ALTER TABLE `zmaneyhayom` ADD FOREIGN KEY ( `zman_id` ) REFERENCES `luah_v2`.`zmaneyhayomlabels` (
`id`
) ON DELETE NO ACTION ON UPDATE NO ACTION ;
I have no idea why it's failing :/
What I want is that whenever I go on phpmyadmin and go to the first table, instead of typing some id in zman_id I will have a select box which I can select a name (which is stored in the second table) but the value it will store will be the ID.
they are not same type id is INT and zman_id is varchar.
you can change this
`zman_id` varchar(255) NOT NULL,
to
`zman_id` int(11) NOT NULL,

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