Mapping (join) create table not allowing foreign keys? - mysql

I have these two tables for this site I'm building (login and licks). I want to allow the user to save his favorite licks so this means I need a mapping table but it's not working. It works without the foreign key constraint but I want/need the foreign key constraint. I've done research and everyone says to create the mapping table as I am but it's not working.
Can anyone tell me why this wont work? Thank you.
Table: Login
CREATE TABLE `login` (
`login_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
PRIMARY KEY (`login_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
Table: Licks
CREATE TABLE `licks` (
`lick_id` int(11) NOT NULL AUTO_INCREMENT,
`lick_name` varchar(50) DEFAULT NULL,
`lick_category` varchar(20) DEFAULT NULL,
`lick_html_pg` varchar(50) DEFAULT NULL,
PRIMARY KEY (`lick_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1
Table login_licks (Not woking!)
CREATE TABLE login_lick (
login_id INT NOT NULL,
lick_id INT NOT NULL,
PRIMARY KEY (login_id, lick_id),
FOREIGN KEY login_id REFERENCES login (login_id),
FOREIGN KEY lick_id REFERENCES licks (lick_id)
);

You are missing parentheses in the foreign key definition:
CREATE TABLE login_lick (
login_id INT NOT NULL,
lick_id INT NOT NULL,
PRIMARY KEY (login_id, lick_id),
FOREIGN KEY (login_id) REFERENCES login (login_id),
FOREIGN KEY (lick_id) REFERENCES licks (lick_id)
);
Here is a SQL Fiddle.

Related

Error creating foreign key on userid, followerid (check data types)

Hey I'm having issues setting foreign keys pointing from my followings table:
CREATE TABLE `followings` (
`id` int(26) NOT NULL,
`userid` varchar(256) NOT NULL,
`followerid` varchar(256) NOT NULL,
`time` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
to my users table:
CREATE TABLE `users` (
`id` int(26) NOT NULL,
`userid` varchar(256) NOT NULL,
`handle` varchar(256) NOT NULL,
`email` varchar(256) NOT NULL,
`password` varchar(256) NOT NULL,
`phone` varchar(256) NOT NULL,
`dateofbirth` varchar(99) NOT NULL,
`phoneverified` varchar(25) DEFAULT NULL,
`emailverified` varchar(25) DEFAULT NULL,
`authentic` tinyint(1) NOT NULL DEFAULT 0,
`datecreated` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `userid` (`userid`),
ADD UNIQUE KEY `handle` (`handle`);
I have checked the collation etc of the fields are the same yet i am still getting an error on phpmyadmin
Error creating foreign key on userid, followerid (check data types)
Any possible reasons for such error
This is the sql generated by phpmyadmin before the error
ALTER TABLE `followings` ADD FOREIGN KEY (`userid`, `followerid`) REFERENCES `users`(`userid`, `userid`) ON DELETE RESTRICT ON UPDATE RESTRICT;
You shouldn't be making a multi-key foreign key. You need separate foreign keys for userid and followerid, since they refer to different rows in the users table.
ALTER TABLE followings ADD FOREIGN KEY (userid) REFERENCES users (userid);
ALTER TABLE followings ADD FOREIGN KEY (followerid) REFERENCES users (userid);
Also, it's usually preferable to have the foreign key reference the primary key.

Why I am having a this error on phpmyadmin: Error creating foreign key on revision (check data types)?

I´m trying to create Foreign Keys in phpmyadmin, but I get this error:
Error creating foreign key on revision (check data types)
I don´t understand it because the data types are equal. So, what I want is to create a Foreign Key from 'acoustictreatment' to 'filterspecifications' which contains tag, offerid and revision. But I get the error that I mentioned.
This are my tables:
CREATE TABLE `offer` (
`projectid` varchar(20) NOT NULL,
`customer` varchar(255) NOT NULL,
`creator` varchar(255) NOT NULL,
`date` date NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `offer`
ADD PRIMARY KEY (`projectid`,`revision`);
CREATE TABLE `filterspecifications` (
`tag` varchar(100) NOT NULL,
`gasFlow` double NOT NULL,
`dustToHandle` double NOT NULL,
`offerid` varchar(20) NOT NULL,
`selectedFilter` varchar(20) NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `filterspecifications`
ADD PRIMARY KEY (`tag`,`offerid`,`revision`),
ADD KEY `offerid` (`offerid`,`revision`);
ALTER TABLE `filterspecifications`
ADD CONSTRAINT `filterspecifications_ibfk_1`
FOREIGN KEY (`offerid`,`revision`) REFERENCES `offer` (`projectid`, `revision`) ON DELETE CASCADE ON UPDATE CASCADE;
CREATE TABLE `acoustictreatment` (
`tag` varchar(100) NOT NULL,
`offerid` varchar(20) NOT NULL,
`outputFanSilencer` tinyint(1) NOT NULL,
`fanAcousticInsulation` tinyint(1) NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `acoustictreatment`
ADD PRIMARY KEY (`tag`,`offerid`,`revision`);
The solution that I found is to delete the 'acoustictreatment' table and create it again with the foreign key from the beginning. Because what I was trying to do was to create all the tables and then create the foreign keys, but that didn´t work for me

Edit an improperly created constraint

I think I may have wrongly created a constraint. I have three tables: Activity, Authentication, Login. I wanted Authentication to be the "primary" table, where I would insert data to create a user, and his details. It would have a one-one relation (id in Login to id in Authentication) with the newly created table, Authentication which stores session ids. The third table would have a one-many relation with multiple rows for AuthenticationID which corresponds to id of Login.
This is what I've created:
| Login | CREATE TABLE `Login` (
`id` int(6) unsigned NOT NULL AUTO_INCREMENT,
`TimeLoggedIn` text NOT NULL,
`sessionid` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`),
KEY `id_2` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1 |
| Authentication | CREATE TABLE `Authentication` (
`id` int(6) unsigned NOT NULL AUTO_INCREMENT,
`userid` varchar(30) NOT NULL,
`password` varchar(30) NOT NULL,
`role` varchar(20) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`AuthenticationID` int(6) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `Authentication_ibfk_1` FOREIGN KEY (`id`) REFERENCES `Login` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1 |
| Activity | CREATE TABLE `Activity` (
`num` int(11) NOT NULL AUTO_INCREMENT,
`AuthenticationID` int(6) unsigned NOT NULL,
`TorrentMag` mediumtext NOT NULL,
PRIMARY KEY (`num`),
KEY `FK_myKey2` (`AuthenticationID`),
CONSTRAINT `FK_myKey` FOREIGN KEY (`AuthenticationID`) REFERENCES `Authentication` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_myKey2` FOREIGN KEY (`AuthenticationID`) REFERENCES `Authentication` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=104 DEFAULT CHARSET=latin1 |
Unfortunately, when I tried to insert a new row into Authentication (which used to work till I created the constraint),
INSERT INTO Authentication (userid, password, role, email) VALUES ("user", "SeG^SU;B2_&Uhw", "user", "someone#mydomain.com");
it gave the error:
Cannot add or update a child row: a foreign key constraint fails (`episodescopy`.`Authentication`, CONSTRAINT `Authentication_ibfk_1` FOREIGN KEY (`id`) REFERENCES `Login` (`id`))
So I've inadvertently created an inverse relation of what I needed? Also I seem to have created a duplicate constraint on table Activity? How can I fix this?
Here is a suggestion which would hopefully at least point you in the right direction. If you want to create users in the Authentication table, then any other table column which references the primary key of Authentication (namely the id) should be declared as a foreign key reference.
CREATE TABLE Login (
id int(6) unsigned NOT NULL AUTO_INCREMENT,
TimeLoggedIn text NOT NULL,
sessionid varchar(255) NOT NULL,
PRIMARY KEY (id),
KEY id (id),
KEY id_2 (id),
CONSTRAINT fk_1 FOREIGN KEY (id) REFERENCES Authentication (id)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1
CREATE TABLE Authentication (
id int(6) unsigned NOT NULL AUTO_INCREMENT,
userid varchar(30) NOT NULL,
password varchar(30) NOT NULL,
role varchar(20) NOT NULL,
email varchar(50) DEFAULT NULL,
AuthenticationID int(6) unsigned DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1
Your current setup is the opposite, requiring a user to exist in Login before it can be inserted into Authentication.

MySQL Error 1215: Cannot add foreign key constraint between Parent and Children

I am utterly disappointed as I failed to pinpoint to the exact reason, why my table creation is failing when I am trying to create a Foreign Key relation between my two tables. The SQL queries that I am using to create the 2 tables are as under:
CREATE TABLE `OneMD_DEA_EMEA_STG_CUSTOMER` (
`Customer_Pkey` int(11) NOT NULL AUTO_INCREMENT,
`CustomerID` varchar(15) NOT NULL,
`DataType` varchar(10) NOT NULL,
`SourceSystemName` varchar(10) NOT NULL,
`SourceCountry` varchar(2) NOT NULL,
`SrcDataRfrshDt` date NOT NULL,
`StartDt` date NOT NULL,
`EndDt` date NOT NULL,
`Category` varchar(50) DEFAULT NULL,
PRIMARY KEY (`Customer_Pkey`,`CustomerID`),
UNIQUE KEY `CustomerID_UNIQUE` (`CustomerID`),
KEY `idx_OneMD_DEA_EMEA_STG_CUSTOMER` (`DataType`,`SrcDataRfrshDt`,`SourceCountry`,`EndDt`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `STG_RELATION` (
`Relation_Pkey` int(11) NOT NULL AUTO_INCREMENT,
`RelationType` varchar(15) NOT NULL,
`SourceDataType` varchar(5) NOT NULL,
`SourceID` varchar(15) NOT NULL,
`TargetDataType` varchar(5) NOT NULL,
`TargetID` varchar(15) NOT NULL,
`RltnPrmryID` varchar(50) NOT NULL,
`SourceSystemName` varchar(10) DEFAULT NULL,
`SourceCountry` varchar(2) NOT NULL,
`SrcDataRfrshDt` date NOT NULL,
`StartDt` date NOT NULL,
`EndDt` date NOT NULL,
`HCPHCOSubType` varchar(10) DEFAULT NULL,
`HCPHCOLinkType` varchar(10) DEFAULT NULL,
`HCOHCOSubType` varchar(10) DEFAULT NULL,
`HCOHCOLinkType` varchar(10) DEFAULT NULL,
PRIMARY KEY (`Relation_Pkey`,`SourceID`,`TargetID`,`RltnPrmryID`),
UNIQUE KEY `Relation_Pkey_UNIQUE` (`Relation_Pkey`),
KEY `idx_STG_RELATION` (`RelationType`,`SrcDataRfrshDt`,`SourceCountry`,`EndDt`),
KEY `Source_ID_idx` (`SourceID`),
KEY `Target_ID_idx` (`TargetID`),
CONSTRAINT `Source_ID` FOREIGN KEY (`SourceID`) REFERENCES `STG_CUSTOMER` (`CustomerID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `Target_ID` FOREIGN KEY (`TargetID`) REFERENCES `STG_CUSTOMER` (`CustomerID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `STG_RELATION_ROLE` (
`RltnRole_PKey` int(11) NOT NULL AUTO_INCREMENT,
`SourceSystemName` varchar(10) NOT NULL,
`ActivityID` varchar(15) NOT NULL,
`RltnFrgnID` varchar(50) NOT NULL,
`SrcDataRfrshDt` date NOT NULL,
`StartDt` date NOT NULL,
`EndDt` date NOT NULL,
`SourceCountry` varchar(2) NOT NULL,
`HCPHCORoleType` varchar(10) DEFAULT NULL,
`HCPHCORoleField` varchar(10) DEFAULT NULL,
`HCPHCORole` varchar(10) DEFAULT NULL,
`HCPHCORoleStatus` varchar(20) DEFAULT NULL,
PRIMARY KEY (`RltnRole_PKey`,`SourceSystemName`,`ActivityID`,`RltnFrgnID`),
KEY `idx_STG_RELATION_ROLE` (`SrcDataRfrshDt`,`SourceSystemName`,`SourceCountry`,`EndDt`),
KEY `Rltn_Frgn_ID_idx` (`RltnFrgnID`),
CONSTRAINT `RltnFrgnID` FOREIGN KEY (`RltnFrgnID`) REFERENCES `STG_RELATION` (`RltnPrmryID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The Table RELATION got created successfully, but whenver I am trying to create the child table (RELATION_ROLE with parent as RELATION), the table creation is failing with the
Error 1215: Cannot Add Foreign Key Constraint
error message.
Am I missing something here?
Please note that CUSTOMER is the main table with child as RELATION (Customer_ID acting as Primary and Foreign Key) which further has a child RELATION_ROLE (RltnPrmryID is the Primary Key while RltnFrgnID is the foreign key.
Please help me to get the issue resolved.
Uh, there are quite a few problems there - in particular with your table designs.
First of all, the STG_RELATION.RltnPrmryID is not the left most field of any indexes. MySQL requires both endpoints of a foreign key to be the leftmost fields of an index. The leftmost fields are the ones that can be used for lookups. This is the direct reason of the error.
Secondly, the primary key of STG_RELATION table is a mess. The child table should reference the primary key or a unique key from the parent table. STG_RELATION.RltnPrmryID is neither, it is only part of the primary key. Relation_Pkey field being auto increment already uniquely identifies records within the STG_RELATION table, therefore this should be the PK and STG_RELATION_ROLE table should reference this column in the foreign key (obviously, you need to adjust the field type for this to work in STG_RELATION_ROLE). Indexes on integers are a lot more efficient than indexes on strings from a performance point of view.

Error Code: 1215. Cannot add foreign key constraint MySQL

Does anybody know why I have the error
Error Code: 1215. Cannot add foreign key constraint
When I try
ALTER TABLE hermanos ADD CONSTRAINT fk_hno_provincia FOREIGN KEY (provincia) REFERENCES p_provincias (id)
On these tables:
CREATE TABLE IF NOT EXISTS `hermanos` (
`codigo` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(255) NOT NULL,
`apellidos` varchar(255) NOT NULL,
`direccion` varchar(255) NOT NULL,
`codigoPostal` int(11) NOT NULL,
`provincia` int(11) NOT NULL,
`numeroHermano` int(11) NOT NULL,
`dni` varchar(9) NOT NULL,
`tipoCuota` int(11) NOT NULL,
`sexo` int(11) NOT NULL,
PRIMARY KEY (`codigo`),
KEY `sexo` (`sexo`),
KEY `pk_hno_cuota` (`tipoCuota`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
CREATE TABLE IF NOT EXISTS `p_provincias` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(125) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=53 ;
Thanks
The parent and child tables must use the same storage engine.
I noticed that hermanos uses InnoDB and p_provincias uses MyISAM.
For more info, see here
Foreign keys definitions are subject to the following conditions:
Foreign key relationships involve a parent table that holds the
central data values, and a child table with identical values pointing
back to its parent. The FOREIGN KEY clause is specified in the child
table. The parent and child tables must use the same storage engine.
They must not be TEMPORARY tables.