I don't get whats wrong with the mysql syntax - mysql

CREATE TABLE hoofdtoonder
(
id INT NOT NULL,
idondersoorten INT FOREIGN KEY REFERENCES `ondersoort`(`id`) NOT NULL,
)
//making table but the error is with the references its on a mysql database someone please help
It says error at FOREIGN KEY REFERENCES ondersoort(id) NOT NULL. But I don't know what's wrong with the syntax.

There are several things wrong here:
First, for an inline constraint, you don't need to specify foreign key, just references.
The not null clause should come before the references clause.
You have a redundant comma at the end of the last column's specification.
To put it all together:
CREATE TABLE hoofdtoonder (
id INT NOT NULL,
idondersoorten INT NOT NULL REFERENCES `ondersoort`(`id`)
);

MySQL does not support inline foreign key references.
It's true that the SQL language allows for syntax like #Mureinik suggested:
idondersoorten INT NOT NULL REFERENCES `ondersoort`(`id`)
But you will find that MySQL parses this and ignores it. InnoDB does not support inline foreign key syntax. If you now run SHOW CREATE TABLE hoofdtoonder, it'll show this:
CREATE TABLE `hoofdtoonder` (
`id` int(11) NOT NULL,
`idondersoorten` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Where did the REFERENCES go? It was silently discarded. This is actually a beef I have with MySQL, that it recognizes some valid constraint syntax, but ignores it. It doesn't even show you a warning. It just defines the table without the constraint.
In MySQL, you must declare a foreign key as a table-level constraint, like this:
CREATE TABLE hoofdtoonder (
id INT NOT NULL,
idondersoorten INT NOT NULL,
FOREIGN KEY (idondersoorten) REFERENCES `ondersoort`(`id`)
);

Related

Error on creating foreign key relationship between non-primary key

I have two table
CREATE TABLE `abc` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ref_id` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ref_id_UNIQUE` (`ref_id`)
)
CREATE TABLE `xyz` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ref_id` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ref_id_UNIQUE` (`ref_id`)
)
I want to make foreign key relation ship between xyz's ref_id and abc's ref_id .But Mysql gives error 1215.
You should make the foreign key relationships to the primary keys. I know that MySQL allows foreign key relationships to anything with an index. But the correct practice is to use primary keys.
So declare the table like this:
CREATE TABLE `xyz` (
`id` int(11) NOT NULL AUTO_INCREMENT,
abc_id int DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ref_id_UNIQUE` (`abc_id`),
ADD CONSTRAINT fk_xyz_abc FOREIGN KEY (abc_id) REFERENCES abc(id)
);
If you want the ref_id for an xyz row, then use JOIN to get the information.
Take a look at Gordon Linoff's answer, his suggestion makes sense, even though it does not answer the question. So what can cause an error when you intend to create a foreign key relationship? The obvious possibility is syntax error and typo, so you will need to check against those and fix any such problems.
Another possibility is that you have inconsistency, that is, you try to create a foreign key constraint in one of your tables, but not all the values have exact matches. So, assuming that you have Foo and Bar table and you intend Foo.lorem to be a foreign key referencing Bar.ipsum, then you will need to ensure that all the values you have for Foo.lorem has a Bar.ipsum pair with the exact same values (except null). If that's not true, then your foreign key constraint will not be successfully created. Find such inconsistencies:
select distinct Foo.lorem
from Foo
where not (Foo.lorem is null) and
not exists (select 1 from Bar where Foo.lorem = Bar.ipsum);
Read the lines carefully and make sure you fix any such Foo.lorem values.

Foreign keys on create table doesn't get created

Executing my code didn't cause errors and didn't create the expected keys on this server:
create table table1 (
id int not null auto_increment primary key,
name varchar(10) not null default ''
) engine=innodb;
create table table2 (
id int not null auto_increment primary key,
idTable1 int null references table1(id) on delete cascade
) engine=innodb;
I've seen some declaring the constraints as:
columnName int not null, foreign key (columnName) references table1(id) on delete cascade
but I think I've already used the previous syntax before and it worked on a different server. I just can't remember for sure.
Have you seen this before? Am I wrong in assuming my syntax would work as it works on MSSQL? If so, why this doesn't cause an error to be thrown?
Edit.:
InnoDB is enabled and set to default with SET storage_engine=INNODB; before running the queries to make sure.
Keys added with the second syntax example work. Keys added with alter table work also.
MySQL doesn't support column level Foreign key constraint addition to the CREATE syntax.
It has to be table level.
Furthermore, MySQL does not recognize or support “inline REFERENCES
specifications” (as defined in the SQL standard) where the references
are defined as part of the column specification. MySQL accepts
REFERENCES clauses only when specified as part of a separate FOREIGN
KEY specification. For storage engines that do not support foreign
keys (such as MyISAM), MySQL Server parses and ignores foreign key
specifications.
Further reading: here

Can't write; duplicate key in table

-- Table Project_DB.Product_table
CREATE TABLE IF NOT EXISTS `Project_DB`.`Product_table`
(
`Product_id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`User_id_fk` INT UNSIGNED NOT NULL ,
`Product_Category_id` INT UNSIGNED NOT NULL ,
`Product_Name` VARCHAR( 45 ) NOT NULL ,
`Product_Price` INT UNSIGNED NOT NULL ,
`Product_details` MEDIUMTEXT NULL ,
PRIMARY KEY ( `Product_id` ) ,
INDEX `User_id_idx` ( `User_id_fk` ASC ) ,
CONSTRAINT `User_id` FOREIGN KEY ( `User_id_fk` )
REFERENCES `Project_DB`.`Registration_table` ( `User_id` )
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE = INNODB;
MySQL said: Documentation
#1022 - Can't write; duplicate key in table 'product_table'
The Database Schema Cannot have two or more FOREIGN KEY with same name. I change all FOREIGN KEYS to different names in my DB Schema then it works...
I recommend you try removing the line
INDEX `User_id_idx` ( `User_id_fk` ASC ) ,
Either that, or remove the foreign key constraint from the table definition, and add that in a separate ALTER TABLE statement.
InnoDB automatically creates the required index when a foreign key constraint is added, or uses a suitable index if it's already there.
I believe the error is occurring because InnoDB is attempting to create an index for the foreign key, rather than using the index that was defined previously. That is, when the CREATE TABLE statement (as posted by OP) is processed, InnoDB is attempting to create both the index defined on User_id_fk, and the index required for the foreign key.
And those two indexes are "duplicates" of each other.
The workaround is to modify the CREATE TABLE statement, to avoid InnoDB attempting to create "duplicate" indexes.
I had the same problem, MySQLWorkbench was working fine when I forward engineered a build script and then it decided to throw it's toys out of the pram.
I fixed the problem by dropping my database in phpMyAdmin and then ran the script again from MySQLWorkbench and it worked. I suspect I'd changed something that caused a conflict.
I know this is an extreme measure; others have said, to go through the DB schema and find duplicates.
Usually, you already use that constraint in another table that you also use for foreign key.

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.

How to code a foreign key in sql?

Hi this is the table I am trying to create:
CREATE TABLE images
(
id PRIMARY KEY NOT NULL INT,
product_id FOREIGN KEY NOT NULL INT,
src varchar(255) NOT NULL
)
But its not letting me (I am getting a syntax error). Anyone have any ideas?
CREATE TABLE IMAGES(
Id int NOT NULL,
PRODUCT_ID int NOT NULL,
src varchar(255) NOT NULL,
PRIMARY KEY (Id),
FOREIGN KEY (P_Id) REFERENCES PRODUCTS(P_Id)
)
and make sure you build the Products table first , and do the reference foreign key
Check out InnoDB Foreign Key Constraints for the right syntax to use. In particular, you need to declare the column you're referencing when you create a foreign key.
Additionally, since you're using MySQL, make sure your tables use InnoDB, otherwise the foreign keys won't actually get enforced.