CREATE TABLE nodes (
id INTEGER PRIMARY KEY NOT NULL,
lat REAL,
lon REAL,
user TEXT,
uid INTEGER,
version INTEGER,
changeset INTEGER,
timestamp TEXT
); # this worked
CREATE TABLE nodes_tags (
id INTEGER,
key TEXT,
value TEXT,
type TEXT,
FOREIGN KEY (id) REFERENCES nodes(id)
); # this did not work
CREATE TABLE ways (
id INTEGER PRIMARY KEY NOT NULL,
user TEXT,
uid INTEGER,
version TEXT,
changeset INTEGER,
timestamp TEXT
); # this worked
CREATE TABLE ways_tags (
id INTEGER NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
type TEXT,
FOREIGN KEY (id) REFERENCES ways(id)
); # this did not work
CREATE TABLE ways_nodes (
id INTEGER NOT NULL,
node_id INTEGER NOT NULL,
position INTEGER NOT NULL,
FOREIGN KEY (id) REFERENCES ways(id),
FOREIGN KEY (node_id) REFERENCES nodes(id)
); # this did not work
Error Code: 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 ' value TEXT, type TEXT, FOREIGN KEY
(id) REFERENCES nodes(id) )' at line 3
comma not valid input at this position
Key is a Reserved Keyword in MySQL. You should really avoid using it as a Table/Column Name. Consider naming it to something else; otherwise you will have to use backticks around it.
CREATE TABLE nodes_tags (
id INTEGER,
`key` TEXT, -- I'd prefer renaming it. eg: node_key
value TEXT,
type TEXT,
FOREIGN KEY (id) REFERENCES nodes(id)
);
CREATE TABLE ways_tags (
id INTEGER NOT NULL,
`key` TEXT NOT NULL, -- I'd prefer renaming it. eg: ways_tags_key
value TEXT NOT NULL,
type TEXT,
FOREIGN KEY (id) REFERENCES ways(id)
);
Related
Hello I have an issue when trying inserting multiple foreign keys to a table. I have searched a lot of hours and still I don't figure it out.. It pops this error. I don't know what else I can do about that. Also I tried to add constraint .. foreign key ... references command and it didn't work.
DROP DATABASE IF EXISTS db;
CREATE DATABASE db;
USE db;
CREATE TABLE BOOKS(
Bno int not null primary key auto_increment,
Title text,
PDate date,
Cno int,
Cname text
);
CREATE TABLE AUTHORS(
Ano int not null primary key auto_increment,
Asurname text,
Aname text
);
CREATE TABLE CATEGORIES(
Cno int not null primary key auto_increment,
Cname text,
No_Of_Books int
);
CREATE TABLE SUMMARY_LANG(
Bno int not null primary key auto_increment,
Language text,
FOREIGN KEY (Bno) REFERENCES BOOKS(Bno)
);
CREATE TABLE WRITER(
Bno int,
Ano int,
Asurname text,
Aname text,
FOREIGN KEY (Bno) REFERENCES BOOKS(Bno),
FOREIGN KEY (Ano) REFERENCES AUTHORS(Ano),
FOREIGN KEY (Asurname) REFERENCES AUTHORS(Asurname),
FOREIGN KEY (Aname) REFERENCES AUTHORS(Aname)
);
INSERT INTO BOOKS(Title,PDate,Cname)
VALUES
('A first course in database systems','2014-01-01','DATABASE'),
('FUNDAMENTAL CONCEPTS OF PROGRAMMING SYSTEMS','1976-01-01','PROGRAMMING');
ALTER TABLE AUTHORS auto_increment = 100;
INSERT INTO AUTHORS(Asurname,Aname)
VALUES
('ULLMAN','JEFF'),
('WIDOM','JENNIFER');
ALTER TABLE CATEGORIES auto_increment = 10;
INSERT INTO CATEGORIES(Cname, No_Of_Books)
VALUES
('DATABASE',1),
('PROGRAMMING',1);
INSERT INTO SUMMARY_LANG(Language)
VALUES
('ENG'),
('GRE'),
('ENG'),
('FRA');
Your definition of SUMMARY_LANG is wrong
CREATE TABLE SUMMARY_LANG(
Bno int not null primary key auto_increment,
Language text,
FOREIGN KEY (Bno) REFERENCES BOOKS(Bno) <-- remove this reference
);
Remove the foreign key, because this is a Table that is used only as reference number to another table also called a helper table, because the text would be redundant in the referenced table.
But i can't see any column that references language.
So add a column to BOOKS, where you add the reference to SUMMARY_LANG and when you add new rows SUMMARY_LANG you won't get any errors anymore.
So the new tables can be like this
CREATE TABLE BOOKS (
Bno INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
Title TEXT,
PDate DATE,
Cno INT,
Cname TEXT,
SNno int,
FOREIGN KEY (SNno)
REFERENCES SUMMARY_LANG (SNno)
);
CREATE TABLE SUMMARY_LANG(
SNno int not null primary key auto_increment,
Language text
);
The first table was created with no problems:
mysql > CREATE TABLE nodes(
-> id varchar(10) PRIMARY KEY,
-> user text,
-> uid varchar(10),
-> version tinyint,
-> changeset smallint,
-> timestamp timestamp
-> );
It is when I tried to create the second table that MySQL is outputting an error:
mysql > CREATE TABLE node_tags(
-> id varchar(10),
-> key text,
-> value text,
-> type text,
-> CONSTRAINT pk_node_tag PRIMARY KEY (id, key),
-> CONSTRAINT fk_node_tags_id FOREIGN KEY (id)
-> REFERENCES nodes (id)
-> );
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 '
value text,
type text,
CONSTRAINT pk_node_tag PRIMARY KEY (id, key),
CONSTRAINT' at line 3
This succeeds. Key is a reserved word, so it needs back-ticks.
Also, a text in an index limits it size as to how much of it can be indexed. It is influenced by your character set in force.
So the following runs thru:
drop table if exists nodes;
CREATE TABLE nodes
( id varchar(10) PRIMARY KEY,
user text,
uid varchar(10),
version tinyint,
changeset smallint,
timestamp timestamp
)engine=innodb;
drop table if exists node_tags;
CREATE TABLE node_tags
( id varchar(10) not null,
`key` text,
value text,
type text,
CONSTRAINT pk_node_tag PRIMARY KEY (id, `key`(255)),
CONSTRAINT fk_node_tags_id FOREIGN KEY (id) REFERENCES nodes (id)
)engine=innodb;
I would highly suggest not having a TEXT in a primary key anyway.
Reserved keywords such as 'key, value, timestamp etc' shouldn't be preferred while creating columns. This induces bugs and isn't scalable.
As far as this is concerned, using backticks key will solve the issue here.
because key is the reserved word in MySQL. please refer to this document to see list of the reserved words: https://dev.mysql.com/doc/refman/5.5/en/keywords.html
i got these two succesfull queries:
create table Donors (
donor_id int not null auto_increment primary key,
gender varchar(1) not null,
date_of_birth date not null,
first_name varchar(20) not null,
middle_name varchar(20),
last_name varchar(30) not null,
home_phone tinyint(10),
work_phone tinyint(10),
cell_mobile_phone tinyint(10),
medical_condition text,
other_details text );
and
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id) );
but when i try this one:
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code),
foreign key(condition_code) references Donors_Medical_Condition(condition_code) );
i get "Error Code: 1215, cannot add foreign key constraint"
i dont know what am i doing wrong.
In MySql, a foreign key reference needs to reference to an index (including primary key), where the first part of the index matches the foreign key field. If you create an an index on condition_code or change the primary key st that condition_code is first you should be able to create the index.
To define a foreign key, the referenced parent field must have an index defined on it.
As per documentation on foreign key constraints:
REFERENCES tbl_name (index_col_name,...)
Define an INDEX on condition_code in parent table Donors_Medical_Condition and it should be working.
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
KEY ( condition_code ), -- <---- this is newly added index key
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id) );
But it seems you defined your tables order and references wrongly.
You should have defined foreign key in Donors_Medical_Condition table but not in Donors_Medical_Conditions table. The latter seems to be a parent.
Modify your script accordingly.
They should be written as:
-- create parent table first ( general practice )
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code)
);
-- child table of Medical_Conditions
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id),
foreign key(condition_code)
references Donors_Medical_Condition(condition_code)
);
Refer to:
MySQL Using FOREIGN KEY Constraints
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION
A workaround for those who need a quick how-to:
FYI: My issue was NOT caused by the inconsistency of the columns’ data types/sizes, collation or InnoDB storage engine.
How to:
Download a MySQL workbench and use it’s GUI to add foreign key. That’s it!
Why:
The error DOES have something to do with indexes. I learned this from the DML script automatically generated by the MySQL workbench. Which also helped me to rule out all those inconsistency possibilities.It applies to one of the conditions to which the foreign key definition subject. That is: “MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan.” Here is the official statement: http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html
I did not get the idea of adding an index ON the foreign key column(in the child table), only paid attention to the referenced TO column(in the parent table).
Here is the auto-generated script(PHONE.PERSON_ID did not have index originally):
ALTER TABLE `netctoss`.`phone`
ADD INDEX `personfk_idx` (`PERSON_ID` ASC);
ALTER TABLE `netctoss`.`phone`
ADD CONSTRAINT `personfk`
FOREIGN KEY (`PERSON_ID`)
REFERENCES `netctoss`.`person` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
I think you've got your tables a bit backwards. I'm assuming that Donors_Medical_Condtion links donors and medical conditions, so you want a foreign key for donors and conditions on that table.
UPDATED
Ok, you're also creating your tables in the wrong order. Here's the entire script:
create table Donors (
donor_id int not null auto_increment primary key,
gender varchar(1) not null,
date_of_birth date not null,
first_name varchar(20) not null,
middle_name varchar(20),
last_name varchar(30) not null,
home_phone tinyint(10),
work_phone tinyint(10),
cell_mobile_phone tinyint(10),
medical_condition text,
other_details text );
create table Medical_Conditions (
condition_code int not null,
condition_name varchar(50) not null,
condition_description text,
other_details text,
primary key(condition_code) );
create table Donors_Medical_Condition (
donor_id int not null,
condition_code int not null,
seriousness text,
primary key(donor_id, condition_code),
foreign key(donor_id) references Donors(donor_id),
foreign key(condition_code) references Medical_Conditions(condition_code) );
I got the same issue and as per given answers, I verified all datatype and reference but every time I recreate my tables I get this error. After spending couple of hours I came to know below command which gave me inside of error-
SHOW ENGINE INNODB STATUS;
LATEST FOREIGN KEY ERROR
------------------------
2015-05-16 00:55:24 12af3b000 Error in foreign key constraint of table letmecall/lmc_service_result_ext:
there is no index in referenced table which would contain
the columns as the first columns, or the data types in the
referenced table do not match the ones in table. Constraint:
,
CONSTRAINT "fk_SERVICE_RESULT_EXT_LMC_SERVICE_RESULT1" FOREIGN KEY ("FK_SERVICE_RESULT") REFERENCES "LMC_SERVICE_RESULT" ("SERVICE_RESULT") ON DELETE NO ACTION ON UPDATE NO ACTION
I removed all relation using mysql workbench but still I see same error. After spending few more minutes, I execute below statement to see all constraint available in DB-
select * from information_schema.table_constraints where
constraint_schema = 'XXXXX'
I was wondering that I have removed all relationship using mysql workbench but still that constraint was there. And the reason was that because this constraint was already created in db.
Since it was my test DB So I dropped DB and when I recreate all table along with this table then it worked. So solution was that this constraint must be deleted from DB before creating new tables.
Check that both fields are the same size and if the referenced field is unsigned then the referencing field should also be unsigned.
I have languages table which looks like that:
-id
-name
-iso
and in multiple tables I need to reference this iso field as foreign key. The problem is, I can't do it even if I give completely unique FK names. What is problem?
Here is how my Languages table contructed:
CREATE TABLE `Languages` (
`id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`iso` char(2) NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`order` tinyint(3) NOT NULL DEFAULT '0',
`active` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
Ensure that you have the same column datatype in your parent and child tables. Also create an index on your parent table's iso column. In absence of details in your question about tables you currently have and SQL you used for them, let's take some examples that you can compare with your database.
Example of different datatype:
create table languages (
id int,
name varchar(100),
iso char(3),
primary key(id)
);
create index ix_countries_iso on languages(iso);
create table countries (
id int,
iso int,
foreign key(iso) references languages(iso)
);
ERROR 1215 (HY000): Cannot add foreign key constraint
Example of missing index on parent table:
create table languages (
id int,
name varchar(100),
iso char(3),
primary key(id)
);
-- notice that we aren't creating an index on iso
create table countries (
id int,
iso char(3), -- notice correct datatype in child and parent table
foreign key(iso) references languages(iso)
);
ERROR 1215 (HY000): Cannot add foreign key constraint
What if you have the same datatype in parent and child but lengths are different? I'd recommend keeping the datatype and the length same but the following statements will work:
create table languages (
id int,
name varchar(100),
iso char(3),
primary key(id)
);
create index ix_countries_iso on languages(iso);
create table countries (
id int,
iso char(10), -- will work, but don't do this
foreign key(iso) references languages(iso)
);
create table countries2 (
id int,
iso char(1), -- will work also, but don't do this
foreign key(iso) references languages(iso)
);
Let's take an example of a working solution of foreign keys that you can compare with your database structure:
create table languages (
id int,
name varchar(100),
iso char(3),
primary key(id)
);
create index ix_countries_iso on languages(iso);
create table countries (
id int,
iso char(3), -- same datatype
foreign key fq_countries_languages(iso) references languages(iso)
);
create table boundaries (
id int,
iso char(3), -- same datatype
foreign key fq_boundaries_languages(iso) references languages(iso)
);
I'd also recommend that your child tables that rely on foreign key should be indexed also. Check out a nice little article on foreign keys.
I'm testing this statement in Safari 5.0.5, but I get an error before FOREIGN:
CREATE TABLE IF NOT EXISTS Idea (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
created TIMESTAMP NOT NULL,
sketchID INTEGER,
categoryID INTEGER NOT NULL,
FOREIGN KEY (sketchID) REFERENCES (Sketch),
FOREIGN KEY (categoryID) REFERENCES (Category));
I get the following error message:
SQLStatementError 1 [DATABASE] near "(": syntax error
Where is the error in this SQL statement?
keeping in mind that even with the correct syntax, foreign key feature is not enabled and could not in web database. because foreign key feature is disabled by default in sqlite3, you have to manually enable it via statement "PRAGMA foreign_keys = ON". Unfortunately, PRAGMA statement is disabled in web database.
good luck!
(Adding my comment as an answer)
As Neil pointed out, you are closing the bracket at the wrong position.
Additionally the syntax for the foreign key is wrong, the following should work (provided the HTML5 SQL dialect is standard compliant)
CREATE TABLE IF NOT EXISTS Idea
(
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
created TIMESTAMP NOT NULL,
sketchID INTEGER,
categoryID INTEGER NOT NULL,
FOREIGN KEY (sketchID) REFERENCES Sketch (sketchId),
FOREIGN KEY (categoryID) REFERENCES Category (categoryId)
);
You need to replace the ) with a , after categoryID INTEGER NOT NULL) so your statement will become:
CREATE TABLE IF NOT EXISTS Idea (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
created TIMESTAMP NOT NULL,
sketchID INTEGER,
categoryID INTEGER NOT NULL,
FOREIGN KEY (sketchID) REFERENCES Sketch (sketchID),
FOREIGN KEY (categoryID) REFERENCES Category (categoryID));
Note the additional bracket at the end of the statement.