mysql: add foreign key after table creation - mysql

I am quite new at mysql.
I am trying to add a foreign key after having created two tables.
Here are the query used to create the tables
CREATE TABLE Categorie_article (
categorie_id INT UNSIGNED,
article_id INT UNSIGNED,
PRIMARY KEY (categorie_id, article_id)
);
CREATE TABLE Article (
id INT UNSIGNED AUTO_INCREMENT,
titre VARCHAR(150) NOT NULL,
texte LONGTEXT NOT NULL,
extrait TEXT,
FULLTEXT KEY (texte),
PRIMARY KEY (id)
);
and here is the query used to create the foreign key constraint:
ALTER Categorie_article ADD CONSTRAINT fk_categorie_article FOREIGN KEY (article_id) REFERENCES Article(id);
And here is the message I got :
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Categorie_article
ADD CONSTRAINT fk_categorie_article FOREIGN KEY (article_' at line 1
Can please someone tell me what I am doing wrong?
I tried to look up at others similar questions but it didn't help.
Thanks in advance ;-)!

The syntax is ALTER TABLE <table_name> not just ALTER <table_name>.
So try:
ALTER TABLE Categorie_article ADD CONSTRAINT fk_categorie_article FOREIGN KEY (article_id) REFERENCES Article(id);
db<>fiddle

Related

why does my foreign key code show a syntax error?

I'm attempting to create a table in a relational database that has a foreign key and a SQL syntax error consistently occurs.
I am using PHP and mySQL (i've removed any non interacting tables that only hold data and don't contribute to the relations)
CREATE table IF NOT EXISTS logins(
loginID int UNSIGNED AUTO_INCREMENT PRIMARY KEY,
buildingID int FOREIGN KEY REFERENCES buildings(buildingID))
buildings is another table, which has the primary key "buildingID"
the error that shows is
Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FOREIGN KEY REFERENCES buildings(buildingID), login varchar(255)...'
this error doesn't happen when the foreign key is removed, the table creates with no errors; and I create this table after i create the table that the foreign key references.
i have tried using the other syntax:
CREATE table IF NOT EXISTS logins(
loginID int UNSIGNED AUTO_INCREMENT,
buildingID int,
PRIMARY KEY(loginID),
FOREIGN KEY (buildingID) REFERENCES buildings(buildingID))
to no avail: the same error happens
what is my mistake here, and how can I change my code to fix it? Thanks.
the error is that primary keys are not permitted to be unsigned, i changed this one thing in my code and the error went away
Few typos.
CREATE table IF NOT EXISTS logins(
loginID int UNSIGNED AUTO_INCREMENT ,
buildingID int,
PRIMARY KEY(loginID),
FOREIGN KEY (buildingID) REFERENCES buildings(buildingID))
this works fine

MariaDB: Error Code: 1005. Can't create table Foreign key constraint is incorrectly formed"

I want to create UserRole table, but mariaDB complains with the following error:
Error Code: 1005. Can't create table `testdb`.`userrole` (errno: 150 "Foreign key constraint is incorrectly formed")
I don't know what I'm doing wrong, below are the tables I want to create.
create table if not exists RoleName (
id varchar(24) not null
);
create table if not exists Usr (
id integer auto_increment,
email varchar(48) not null,
usr_name varchar(48),
is_active bool default false,
constraint usr_pk primary key (id)
);
create table if not exists UserRole (
usr_id integer,
usr_role varchar(24),
constraint usr_role_fk foreign key (usr_id)
references Usr(id),
constraint usr_role_usr_fk foreign key (usr_role)
references RoleName(id)
);
I've searched on SO for solutions, but until now, nothing works. FK and PK are the same.
I got a similar a error
ERROR 1005 (HY000): Can't create table 'rhapsody.#sql-f1a_11e8cd'
when I ran
ALTER TABLE VIEW_TRACKS ADD FOREIGN KEY (TRACK_ID) REFERENCES TRACK(TRACK_ID)
because VIEW_TRACKS.TRACK_ID was defined as a varchar(20) while the
referenced field TRACK.TRACKID was defined as a smallint(6).
As a workaround, I created a new key VIEW_TRACKS.TRACK_PTR of type smallint(6) and created a foreign key that referenced TRACK.TRACK_ID and it worked.
It is also critical that the referenced key - TRACK.TRACKID - be either UNIque or PRImary.

I am trying to create a table with only two foreign key

I have searched a lot but I could get only the concept that this is used for many to many linking. Or separate syntax for foreign key and primary key. But could not correct syntax as a whole.
CREATE TABLE cart
(
Customer varchar(40) FOREIGN KEY REFERENCES users(UserName),
Product varchar(40) FOREIGN KEY REFERENCES products(PID),
CONSTRAINT combination PRIMARY KEY (Customer,Product)
);
I am getting the error
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FOREIGN KEY REFERENCES users(UserName), Product varchar(40) FOREIGN KEY RE' at line 3
Foreign key definitions go after all of the column definitions, they aren't defined inside the column definition. In your case, it would rather be:
CREATE TABLE cart
(
Customer varchar(40),
Product varchar(40),
FOREIGN KEY (Customer) REFERENCES users(UserName),
FOREIGN KEY (Product) REFERENCES products(PID),
PRIMARY KEY (Customer,Product)
);

Have error trying to modify a table in MySQL

I am trying to add a column to my table and make it a foreign key but I keep getting this error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'FOREIGN KEY(idplayer) REFERENCES
players(playersid)' at line 1
below is my code before the alter statement:
CREATE TABLE transactions
(
transid INT UNSIGNED NOT NULL AUTO_INCREMENT,
type VARCHAR(20),
fromteam VARCHAR(30),
toteam VARCHAR(30),
idplayer INT UNSIGNED NOT NULL,
PRIMARY KEY(transid)
);
Now I try to alter the idplayer and make it a foreign key:
ALTER TABLE transactions
MODIFY idplayer INT UNSIGNED NOT NULL
FOREIGN KEY(idplayer) REFERENCES players(playersid)
Please an assistance would be great.
First off, you are missing a comma after NOT NULL, Second you need to tell mysql to add the CONSTRAINT. Give this a try:
ALTER TABLE `events`
MODIFY idplayer INT UNSIGNED NOT NULL,
ADD CONSTRAINT `FK_Name` FOREIGN KEY (idplayer) REFERENCES players(playersid);

MySQL InnoDB Create FK error

I am trying to create a self-referential FK:
DROP TABLE IF EXISTS `Company`;
CREATE TABLE `Company` (
`company_id` INTEGER(32) UNSIGNED AUTO_INCREMENT,
`parent_company_id` INTEGER(32),
PRIMARY KEY (`company_id`)
) ENGINE=InnoDB;
ALTER TABLE `Company`
ADD FOREIGN KEY `parent_company_id` REFERENCES `Company`(`company_id`);
I am getting the following error:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'REFERENCES Company(company_id)' at line 1
Got it.
You gotta change the definition of
parent_company_id INTEGER(32)
To match company_id except for the autoincrement and then use this statement
ALTER TABLE `Company`
ADD CONSTRAINT fk_parent_company_id FOREIGN KEY (`parent_company_id`) REFERENCES `Company`(`company_id`)
So basically remember to put unsigned on the column you are using as FK so it matches the definition of the referenced key