MySQL Foreign Key Reference Syntax - mysql

I am using XAMPP server on Windows PC. Recently i was learning about and working with MySQL relational tables. I was creating a MySQL query to create a table with foreign key reference. My code is as follows:
CREATE TABLE loginattempts (
id int(16) NOT NULL,
loginattempts tinyint(9) NOT NULL,
attemptdate DATETIME NOT NULL
)
FOREIGN KEY (id) REFERENCES users(id)
ON DELETE CASCADE
ON UPDATE CASCADE
ENGINE = INNODB;
I have another table named users in my DB. When i execute the above query i get an error which is something like this:
Error [1064]: MySQL Syntax not correct Correspond to your MariaDB Documentation.
Is there anything wrong in my syntax if so please correct me!
Help will be highly appreciated. The above query is supposed to be written in PHP My Admin.
P.S.(If you find any mistakes feel free to edit)

The definition goes inside the create table statement:
CREATE TABLE loginattempts (
id int(16) NOT NULL,
loginattempts tinyint(9) NOT NULL,
attemptdate DATETIME NOT NULL,
FOREIGN KEY (id) REFERENCES users(id)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE = INNODB;
int(16) and tinyint(9) don't really make sense. An integer has up to 10 possible digits in its representation and a tinyint up to 3.
Often, foreign keys are given names. In addition, I recommend:
Each table have its own id, named after the table (i.e. userId rather than id).
Foreign keys have the same name as the primary key, where possible.
Constraints have names.
So, I would suggest:
CREATE TABLE loginattempts (
loginAttemptId int auto_increment primary key,
userId int NOT NULL,
loginattempts tinyint NOT NULL,
attemptdate DATETIME NOT NULL,
CONSTRAINT fk_loginattempts_userid FOREIGN KEY (userId) REFERENCES users(userId)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE = INNODB;
Of course, this requires changing the users table so the primary key is userId rather than id.
Here is a db<>fiddle.

Related

MySQL Foreign key constraint are incompatible

MySQL Version 8.0.17
The full error reads:
Referencing column 'groupLineId' and referenced column 'groupLineId' in foreign key constraint 'salesItemLine-groupLine' are incompatible
I am trying to link two tables via the groupLineId which are both NOT NULL VARCHAR(12). I am not sure why I am getting the error. I have several other foreign key relationships like this in my DB.
I am using the following code to generate the two tables. (Note: code for invoice table not shown)
CREATE TABLE IF NOT EXISTS `reports`.`groupLine` (
`groupLineId` VARCHAR(12) NOT NULL,
`lineNum` INT NOT NULL,
`invoiceId` VARCHAR(12) NOT NULL,
PRIMARY KEY (`groupLineId`, `lineNum`, `invoiceId`),
INDEX `groupLine-invoice_idx` (`invoiceId` ASC) VISIBLE,
CONSTRAINT `groupLine-invoice`
FOREIGN KEY (`invoiceId`)
REFERENCES `reports`.`invoice` (`invoiceId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `reports`.`salesItemLine` (
`groupLineId` VARCHAR(12) NOT NULL,
`lineNum` INT NOT NULL,
`description` VARCHAR(256) NULL,
`amount` DECIMAL NULL,
`detailType` VARCHAR(45) NULL,
PRIMARY KEY (`groupLineId`, `lineNum`),
INDEX `salesItemLine-groupLine_idx` (`groupLineId` ASC) VISIBLE,
CONSTRAINT `salesItemLine-groupLine`
FOREIGN KEY (`groupLineId`)
REFERENCES `reports`.`groupLine` (`groupLineId`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
If anyone comes across this my problem was how I was making changes and using the "Forward Engineer" feature of MySQL Workbench. I had originally created the database with groupLineId ID as type INT. I then changed the model to make the groupLineId in both tables to VARCHAR(12). Then when I would run "Forward Engineer" it would first write the new groupLine table and change the type of groupLineId to VARCHAR(12) this would then break the existing FROGIEN key with salesItemLine table which has not been updated and still has the type of groupeLineId as INT.
The solution was to DROP both tables before rerunning the forward engineering. (Or at least manually dropping the existing constraints)

MYSQL create table, constraint, foreign key

I am following along with a UDEMY course about SQL. The instructor is working in postgresql. I am working in MySQL workbench. Our corporate development is in MySQL 5.6 on the AWS platform. So I want to learn in MySQL.
There is a lecture about "creating tables" and using constraint and foreign key commands to link the primary keys in two different tables. This is something I want to do with my data, so the challenge is relevant. The instructor's code does not compile for me. I get "error code 1215. Cannot add foreign key constraint".
I have read here that the variables must have the exact same definition. So I changed the instructor's tables from "serial" to int. I am still getting the error. I have tried simplifying the code. I'm still not getting anywhere. Can anybody help me understand why it is not executing?
create table if not exists accounts(
user_id INT auto_increment not null,
username varchar(50) unique not null,
password varchar(50) not null,
email varchar(350) unique not null,
created_on timestamp not null,
last_login timestamp,
primary key (user_id)
);
create table if not exists role(
role_id INT auto_increment not null,
role_name varchar(250) unique not null,
PRIMARY KEY (role_id)
);
create table accounts_role(
user_id INT,
role_id INT,
grant_date timestamp,
primary key (user_id, role_id),
constraint accounts_role_role_id_fkey foreign key (role_id)
references role(role_id) match simple
on update no action
on delete no action,
constraint accounts_role_user_id_fkey foreign key (user_id)
references account (user_id) MATCH SIMPLE
on update no action
on delete no action
);
good grief.
Thanks Caius, i was implementing your suggestion and I found the answer to my problem.
i realized that my table is named "accounts" and i was creating a constraint on "account" ...
create table accounts_role(
user_id INT,
role_id INT,
grant_date timestamp,
primary key (user_id, role_id),
constraint accounts_role_role_id_fkey foreign key (role_id)
references role(role_id) match simple
on update no action
on delete no action,
constraint accounts_role_user_id_fkey foreign key (user_id)
references accounts(user_id) MATCH SIMPLE
on update no action
on delete no action
);

Issues with creating a foreign key

I'm having issues with setting up a relation between 2 tables called Customer and Customer_Number. I have both tables set to InnoDB both have indexes, but when I go to create the foreign key, I get a "no index defined" error. Below are some screen shots
Here Is the Customer table.
Here is the Customer_Number table.
And here is my error message when trying to create the foreign key.
And lastly, this is the error I get when trying to create the relationship manually.
I just can't seem to figure out the issue, and it's driving me nuts!
the output for SHOW CREATE TABLE Customer is
CREATE TABLE `Customer` (
`Customer_ID` int(11) NOT NULL AUTO_INCREMENT,
`First` varchar(255) NOT NULL,
`Last` varchar(255) NOT NULL,
PRIMARY KEY (`Customer_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
and the output for SHOW CREATE TABLE Customer_Number is
CREATE TABLE `Customer_Number` (
`Num_ID` int(11) NOT NULL AUTO_INCREMENT,
`Customer_ID` int(11) NOT NULL,
`Number` varchar(255) NOT NULL,
PRIMARY KEY (`Num_ID`),
KEY `Customer_ID` (`Customer_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
The two CREATE TABLE statements as posted are correct and should be able to accept a new FOREIGN KEY constraint on Customer_Number.Customer_ID since the necessary criteria are met (same data type as referenced column, comparable index or primary key on referenced column).
An ALTER statement succeeds in my testing:
ALTER TABLE Customer_Number ADD FOREIGN KEY (Customer_ID) REFERENCES Customer (Customer_ID);
Being unfamiliar with how PhpMyAdmin abstracts some RDBMS errors, it is hard to say for sure what exactly has gone wrong in the GUI. But if you run the ALTER statement manually and encounter errors about failed foreign key constraints, that's an indication the referencing table already contains values in the column which do not reference a valid row value in the parent table. To uncover those rows so you can address them, execute a query like:
SELECT * FROM Customer_Number WHERE Customer_ID NOT IN (SELECT Customer_ID FROM Customer)
Once you have found the problematic rows, you can either delete them (if unneeded) or update their values to the value of a valid row value in the referenced table. If the column's definition allowed NULL (which yours does not) you could also UPDATE them to set them NULL then run the ALTER statement again.
It is also possible to disable foreign key checks temporarily, add the constraint, update the rows to match valid parent table values, the reenable foreign key checks.
please try this.
alter table Customer_Number add foreign key(customer_ID) references Customer (Customer_ID);

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

I have created two tables in MySQL 5.6.11 as shown below by means of MySQL Workbench 5.2.47.
The country table:
delimiter $$
CREATE TABLE `country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INC
REMENT=2 DEFAULT CHARSET=utf8$$
The state_table:
delimiter $$
CREATE TABLE `state_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state_name` varchar(45) DEFAULT NULL,
`country_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `country_fk` FOREIGN KEY (`id`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT=''$$
There is one row in the country table with the id 1. It allows only one (child) row to be inserted into its child table state_table. If more rows are attempted, then the following error occurs.
ERROR 1452: Cannot add or update a child row: a foreign key constraint
fails (social_networking.state_table, CONSTRAINT country_fk
FOREIGN KEY (id) REFERENCES country (id) ON DELETE CASCADE ON
UPDATE CASCADE)
SQL Statement:
INSERT INTO `social_networking`.`state_table` (`id`, `state_name`, `country_id`) VALUES ('2', 'xxx', '1')
Actually, I'm trying to map these tables using an ORM (JPA) where I always see only OneToOne relationship.
What am I missing?
Well, I find the answer, the solution, my english is not very well but I think can explain you. I get this error after try to create a trigger, My database was created in phpmyadmin, and this error was make me crazy, the problem was that I before create the trigger, I load a lot of data in my tables, and in my child table was some data that have no match in my parent table, ej: my child table "chat" have a "id_jugador=1" and in my parent table there wasn't that "id_jugador", that was my mistake, I hope help you, Argentina Rulz ;)
I think you have a typo in your foreign key constraint, country_id should probaby be the foreign key to country. When id is the foreign key, you can only insert one row since it just happens to get id=1 which is the same id as the row in country;
CONSTRAINT `country_fk` FOREIGN KEY (`id`)
REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
should probably be
CONSTRAINT `country_fk` FOREIGN KEY (`country_id`)
REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
An SQLfiddle to test with.
I had the same problem and it was not wrong relationships name.
I had problem with different records, ie, tried registering a record that did not exist in another table so generated this error.
Check if the record exists in another table to insert their correct relationship, otherwise, this error appears.
Hope this help you.
example:
table1(
id1 INT PRIMARY KEY,
name1 VARCHAR(50)
)
table2(
id2,<--- want to add FOREIGN KEY to this field
name2 VARCHAR(50)
)
Before adding constraint foreign key you must have the right value between id1 and id2, so you should update that id field with the value that map each other.
Possible Solution
if you have live data, then check all column values.
i.e. if you have 'x'->table as primary one having 'a'->column and 'y'->table as secondary with 'b'->column, then all values in 'b'->column must exist in 'a'->column if any value that exists in 'b'->column and not exist in 'a'->column then it will give as such error..
Hope this help.. for newbie..

MySQL Errno 150

I'm creating a few simple tables and I can't get passed this foreign key error and I'm not sure why. Here's the script below.
create TABLE Instructors (
ID varchar(10),
First_Name varchar(50) NOT NULL,
Last_Name varchar(50) NOT NULL,
PRIMARY KEY (ID)
);
create table Courses (
Course_Code varchar(10),
Title varchar(50) NOT NULL,
PRIMARY KEY (Course_Code)
);
create table Sections (
Index_No int,
Course_Code varchar(10),
Instructor_ID varchar(10),
PRIMARY KEY (Index_No),
FOREIGN KEY (Course_Code) REFERENCES Courses(Course_Code)
ON DELETE cascade
ON UPDATE cascade,
FOREIGN KEY (Instructor_ID) REFERENCES Instructors(ID)
ON DELETE set default
);
Error Code: 1005. Can't create table '336_project.sections' (errno: 150)
My data types seem identical and the syntax seems correct. Can anyone point out what I'm not seeing here?
I'm using MySQL Workbench 5.2
This error also occurs if you are relating columns of different types, eg. int in the source table and BigInt in the destination table.
If you're using the InnoDB engine, the ON DELETE SET DEFAULT is your problem. Here's an excerpt from the manual:
While SET DEFAULT is allowed by the MySQL Server, it is rejected as invalid by InnoDB. CREATE TABLE and ALTER TABLE statements using this clause are not allowed for InnoDB tables.
You can use ON DELETE CASCADE or ON DELETE SET NULL, but not ON DELETE SET DEFAULT. There's more information here.
You can run
SHOW ENGINE INNODB STATUS
to read the reason of the failure in a human readable format
e.g.
------------------------
LATEST FOREIGN KEY ERROR
------------------------
150331 15:51:01 Error in foreign key constraint of table foobar/#sql-413_81:
FOREIGN KEY (`user_id`) REFERENCES `foobar`.`users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE:
You have defined a SET NULL condition though some of the columns are defined as NOT NULL.
In order to create a FOREIGN KEY with reference to another table, the keys from both tables should be PRIMARY KEY and with the same datatype.
In your table sections, PRIMARY KEY is of different datatype i.e INT but in another table, it's of type i.e VARCHAR.
It may also be the case if you are not specifying the ON DELETE at all but are trying to reference a MYISAM table from InnoDB table:
CREATE TABLE `table1`(
`id` INT UNSIGNED NOT NULL,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MYISAM CHARACTER SET UTF8;
CREATE TABLE `table2`(
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`table1_id` INT UNSIGNED NOT NULL,
`some_value` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_table1_id`(`table1_id`),
CONSTRAINT FOREIGN KEY (`table1_id`) REFERENCES `table1`(`id`)
) ENGINE=INNODB CHARACTER SET UTF8;
The above will throw errno 150. One need to change the first table to InnoDB too for this to work.
It is failing on the
ON DELETE set default
I have not come across that before and I am not seeing it in the manuals either ( but then it is late )
Update
just seen this in the manual
While SET DEFAULT is allowed by the MySQL Server, it is rejected as
invalid by InnoDB. CREATE TABLE and ALTER TABLE statements using this
clause are not allowed for InnoDB tables.
I guess you may be using InnoDB tables ?
For completeness sake - you will also get this error if you make a foreign reference to a table that isn't defined at the time;
Here Problem is in database engine ( table1 MYISAM and table2 ENGINE).
To set FOREIGN KEYs,
Both table must be in same ENGINE and same charset.
PK column in parent and FK column must be in same data type and same collation type.
Hope you got an idea.
Make sure that table type is InnoDB, MyISAM does not support foreign key, afaik.