MySQL relationship with 2 table - mysql

I have two tables:
CREATE TABLE `companies` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`industry_id` int(11) DEFAULT NULL,
... other fields ...
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and:
CREATE TABLE `industries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I tried to add a foreign key to the second table:
ALTER TABLE industries ADD FOREIGN KEY (id) REFERENCES companies(industry_id) ON DELETE RESTRICT;
But I got next error:
Cannot add foreign key constraint
How can I add right fkey?

I suppose you've done it wrong. Primary key can't be Foreign Key.
Let's make little changes, which can give you the same value
ALTER TABLE companies ADD FOREIGN KEY (industry_id) REFERENCES industries(id) ON DELETE RESTRICT;

Related

mysql add constraint - #1005 - Can't create table ... errno: 121 Duplicate key on write or update

I have been pulling my hair on this one and I am sure it is something small that I can not see...
Here are my 2 tables companies and peoples with many to many relationship and my pivot table company_people :
CREATE TABLE `companies` (
`id` bigint UNSIGNED NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`is_active` int NOT NULL DEFAULT '1',
`company` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `peoples` (
`id` bigint UNSIGNED NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`is_active` int NOT NULL DEFAULT '1',
`firstname` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '',
`lastname` varchar(120) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT '',
`company_id` bigint UNSIGNED DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci PACK_KEYS=0;
CREATE TABLE `company_people` (
`id` bigint NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`company_id` bigint UNSIGNED NOT NULL,
`people_id` bigint UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `companies`
ADD PRIMARY KEY (`id`);
ALTER TABLE `peoples`
ADD PRIMARY KEY (`id`),
ADD KEY `company_id` (`company_id`);
ALTER TABLE `company_people`
ADD PRIMARY KEY (`id`),
ADD KEY `company_id` (`company_id`),
ADD KEY `people_id` (`people_id`);
ALTER TABLE `companies`
MODIFY `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE `peoples`
MODIFY `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE `company_people`
MODIFY `id` bigint NOT NULL AUTO_INCREMENT;
ALTER TABLE `peoples`
ADD CONSTRAINT `peoples-company` FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `company_people`
ADD CONSTRAINT `companies-peoples` FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `company_people`
ADD CONSTRAINT `peoples-companies` FOREIGN KEY (`people_id`) REFERENCES `peoples` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
Everything goes except the last mysql statement which gives the following error : #1005 - Can't create table FairTrade.company_people (errno: 121 "Duplicate key on write or update")
Where is the glitch?
You have an error in
ALTER TABLE `companies`
ADD PRIMARY KEY (`id`),
ADD KEY `company_id` (`company_id`);
get so
Error Code: 1072. Key column 'company_id' doesn't exist in table
so remove the key like
ALTER TABLE `companies`
ADD PRIMARY KEY (`id`)
;
or choose another column

foreign key constraint field set to NULL not working

I want to allow NULL values to a field with foreign key constraint set.
Here's the table schema:
CREATE TABLE `internal_team_head` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`internal_team_id` int(11) NOT NULL,
`users_id` int(11) NOT NULL DEFAULT '0',
`type` enum('lead','project_manager') NOT NULL,
`updated_by` int(6) DEFAULT NULL,
`updated_on` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`,`internal_team_id`,`users_id`,`type`),
KEY `fk_internal_team_has_users_users1_idx` (`users_id`),
KEY `fk_internal_team_has_users_internal_team1_idx` (`internal_team_id`),
CONSTRAINT `fk_internal_team_has_users_internal_team1` FOREIGN KEY (`internal_team_id`) REFERENCES `internal_team` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=69 DEFAULT CHARSET=utf8
Now I want to change users_id to allow NULL values and default to NULL.
ALTER TABLE `internal_team_head` CHANGE `users_id` `users_id` INT(11) NULL DEFAULT NULL;
The Alter query executes successfully but users_id Null attribute is still set to No and default value set to 0.
How do I enforce the changes?
Dropping foreign key constraint first, then running your alter statement should work. You can add the constraint back again after that.

mysql cannot add foreign key for unknown reason

I cannot a add a foreign key constraint. the sql i m running is -
ALTER TABLE image_shout ADD CONSTRAINT `fk_image` FOREIGN KEY (image_id)
REFERENCES images(image_id);
the collation and the data types( int(10) ) are same in the two tables.
mysql says -
Error Code: 1215. Cannot add foreign key constraint
The images table structure -
CREATE TABLE `images` (
`image_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`image_name` varchar(100) CHARACTER SET latin1 NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`caption` varchar(450) CHARACTER SET latin1 DEFAULT NULL,
`image_visibility` int(10) unsigned NOT NULL,
`album_id` int(10) unsigned NOT NULL,
`album_view` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`album_thumb_view` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`image_id`),
KEY `Index_2` (`album_id`),
CONSTRAINT `FK_images_1` FOREIGN KEY (`album_id`) REFERENCES `photo_album` (`Album_ID`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4314 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
The image_shout table -
CREATE TABLE `image_shout` (
`auto_id` int(11) NOT NULL AUTO_INCREMENT,
`shout_id` int(11) DEFAULT NULL,
`image_id` int(10) DEFAULT NULL,
PRIMARY KEY (`auto_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1132 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
UPDATE -
The new error after changing the image_id column to unsigned is -
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails
(`void`.`#sql-36b_7285`, CONSTRAINT `fk_image` FOREIGN KEY (`image_id`)
REFERENCES `images` (`image_id`) ON DELETE SET NULL ON UPDATE CASCADE)
Regards
Is because the image_id in table images is defined as unsigned
`image_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
and in image_shout not
`image_id` int(10) DEFAULT NULL,
Change both columns to the same data type and it should work.
The problem is below. According to the documentation, a foreign key must be indexed. Further, a foreign key should reference the KEY of another table. Not just a column. Try using auto_id as the constraint if you don't wish to change your table structure.
Please see MySQL Documentation for the list of requirements of a Foreign Key constraint.
CREATE TABLE `image_shout` (
`auto_id` int(11) NOT NULL AUTO_INCREMENT,
`shout_id` int(11) DEFAULT NULL,
`image_id` int(10) DEFAULT NULL,
PRIMARY KEY (`auto_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1132 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Error 1452 Foreign Key Fails

I am getting a 1452 error from MySQL. Here is the SQL I used to INSERT
INSERT INTO `Quote` (`QTE_id`, `USR_id`, `QTE_total`, `QTE_desc`, `QTE_dateCreated`, `QTE_dateModified`,`QTE_name`, `QTE_status`)
VALUES
(39, 2, NULL, 'desc', '2013-11-19 00:00:00', '2013-11-19 11:22:49', 'test', 'Active');
Cannot add or update a child row: a foreign key constraint fails (`dbNAME`.`Quote`, CONSTRAINT `USR_id1` FOREIGN KEY (`USR_id`) REFERENCES `users` (`USR_id`))
I am positive that the USR_id I am trying to put into the Quote table exists. Any ideas? A lot of the other questions on Stack Overflow did not answer my question.
Here is the Create syntax for the following tables I am trying to insert and relate (generated from Workbench):
CREATE TABLE `Quote` (
`QTE_id` int(11) NOT NULL AUTO_INCREMENT,
`USR_id` int(11) DEFAULT NULL,
`QTE_total` decimal(7,2) DEFAULT NULL,
`QTE_desc` text,
`QTE_dateCreated` timestamp NULL DEFAULT NULL,
`QTE_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`QTE_name` varchar(255) DEFAULT NULL,
`QTE_status` varchar(30) DEFAULT NULL,
PRIMARY KEY (`QTE_id`),
KEY `USR_id1` (`USR_id`),
CONSTRAINT `USR_id1` FOREIGN KEY (`USR_id`) REFERENCES `users` (`USR_id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;
And the User Table:
CREATE TABLE `Users` (
`USR_id` int(11) NOT NULL AUTO_INCREMENT,
`MGR_id` int(11) NOT NULL DEFAULT '0'
`REP_id` int(11) NOT NULL,
`USR_name` varchar(255) NOT NULL,
`USR_login` varchar(255) NOT NULL,
`USR_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`USR_dateCreated` datetime NOT NULL,
`USR_role` enum('Salesperson','Manager') DEFAULT NULL,
PRIMARY KEY (`USR_id`,`MGR_id`,`REP_id`),
KEY `MGR_id_idx` (`MGR_id`),
KEY `REP_id_idx` (`REP_id`),
KEY `USR_login` (`USR_login`),
CONSTRAINT `MGR_id` FOREIGN KEY (`MGR_id`) REFERENCES `users` (`USR_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `REP_id` FOREIGN KEY (`REP_id`) REFERENCES `representative` (`REP_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
I had to do a few small changes (change the users to Users, add a ',' at the end of line that defines MGR_id, remove the constraint for REP_id) to make the two CREATEs to work.
Here are the exact CREATEs:
CREATE TABLE `Users` (
`USR_id` int(11) NOT NULL AUTO_INCREMENT,
`MGR_id` int(11) NOT NULL DEFAULT '0',
`REP_id` int(11) NOT NULL,
`USR_name` varchar(255) NOT NULL,
`USR_login` varchar(255) NOT NULL,
`USR_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`USR_dateCreated` datetime NOT NULL,
`USR_role` enum('Salesperson','Manager') DEFAULT NULL,
PRIMARY KEY (`USR_id`,`MGR_id`,`REP_id`),
KEY `MGR_id_idx` (`MGR_id`),
KEY `REP_id_idx` (`REP_id`),
KEY `USR_login` (`USR_login`),
CONSTRAINT `MGR_id` FOREIGN KEY (`MGR_id`) REFERENCES `Users` (`USR_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
CREATE TABLE `Quote` (
`QTE_id` int(11) NOT NULL AUTO_INCREMENT,
`USR_id` int(11) DEFAULT NULL,
`QTE_total` decimal(7,2) DEFAULT NULL,
`QTE_desc` text,
`QTE_dateCreated` timestamp NULL DEFAULT NULL,
`QTE_dateModified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`QTE_name` varchar(255) DEFAULT NULL,
`QTE_status` varchar(30) DEFAULT NULL,
PRIMARY KEY (`QTE_id`),
KEY `USR_id1` (`USR_id`),
CONSTRAINT `USR_id1` FOREIGN KEY (`USR_id`) REFERENCES `Users` (`USR_id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;
With that in place the following two INSERTs worked:
mysql> INSERT INTO `Users` (`USR_id`, `MGR_id`) VALUES(2, 2);
Query OK, 1 row affected, 4 warnings (0.22 sec)
mysql> INSERT INTO `Quote` (`QTE_id`, `USR_id`, `QTE_total`, `QTE_desc`, `QTE_dateCreated`, `QTE_dateModified`,`QTE_name`, `QTE_status`) VALUES (39, 2, NULL, 'desc', '2013-11-19 00:00:00', '2013-11-19 11:22:49', 'test', 'Active');
Query OK, 1 row affected (0.22 sec)
I hope this helps.

Put unique index across more than one table

I have run into a problem where the easiest solution would be to add a unique index that goes across multiple tables in mysql. Is this possible?
For the purpose of this question I will have three tables; status, tracks and events. The status and tracks tables both have an auto incrementing ID (T_ID or S_ID) in. Information from them is added to the events table with a trigger. The problem is that there could be the same auto incrementing ID in tracks and status, this means that their could be the same ID more than once in events.
tracks;
CREATE TABLE `tracks` (
`ID` int(11) NOT NULL,
`url` varchar(200) COLLATE latin1_general_ci NOT NULL,
`name` varchar(100) COLLATE latin1_general_ci NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
`T_ID` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`T_ID`),
UNIQUE KEY `url` (`url`),
UNIQUE KEY `T_ID` (`T_ID`),
KEY `ID` (`ID`),
CONSTRAINT `tracks_ibfk_1` FOREIGN KEY (`ID`) REFERENCES `members` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci
status
CREATE TABLE `status` (
`ID` int(11) NOT NULL,
`status` varchar(300) COLLATE latin1_general_ci NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
`S_ID` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`S_ID`),
UNIQUE KEY `S_ID` (`S_ID`),
KEY `ID` (`ID`),
CONSTRAINT `status_ibfk_1` FOREIGN KEY (`ID`) REFERENCES `artists` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci
events
CREATE TABLE `events` (
`ID` int(11) NOT NULL,
`action` varchar(100) COLLATE latin1_general_ci NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
`E_ID` int(11) NOT NULL,
KEY `ID` (`ID`),
CONSTRAINT `events_ibfk_1` FOREIGN KEY (`ID`) REFERENCES `members` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci COMMENT='This table shows what the artist has done and is used feed'
Agreed, you cannot have an index across multiple tables.
However, consider changing your schema by adding a "source" column to your event table and making a unique constraint on the combination of the source and the foreign key. This would prevent duplicate keys being inserted from the same source.