DROP TABLE IF EXISTS CARD_ACCOUNT;
Create Table CARD_ACCOUNT(
acct_no Char(16),
exp_date date,
card_type ENUM('Debit','Credit') NOT NULL,
cust_ID integer NOT NULL
);
DROP TABLE IF EXISTS DEBIT_CARD;
Create Table DEBIT_CARD(
acct_no Char(16),
exp_date date,
bank_no CHAR(9) NOT NULL,
Constraint debit_card_pk primary key(acct_no,exp_date),
Constraint debit_card_fk foreign key(acct_no,exp_date) References card_account(Acct_no,exp_date)
ON UPDATE CASCADE
ON DELETE CASCADE
);
When I try to run this statement I get a "Cannot add foregin key constraint" error in Mysql on the Debit_Card table, why do I get this error the script I am learning from has everything writen the same exact way as I have.
card_account(Acct_no,exp_date) must be Primary Key if you want reference to it in Foreign Key.
and why you don't make it into 1 table?
Create Table CARD_ACCOUNT(
acct_no Char(16),
exp_date date,
bank_no CHAR(9) NOT NULL,
card_type ENUM('Debit','Credit') NOT NULL,
cust_ID integer NOT NULL,
Constraint CARD_ACCOUNT_PK primary key(acct_no,exp_date)
);
i think it serve the same purpose. you already have card_type to know if its debit or credit card so why make separate table for that?
Use the below code, I have just added one primary key constraint in the first table, it will allow you to create the foreign key. But, as "Tim Biegeleisen" commented there is database design problem, you should think again about your database design.
DROP TABLE IF EXISTS CARD_ACCOUNT;
Create Table CARD_ACCOUNT(
acct_no Char(16),
exp_date date,
card_type ENUM('Debit','Credit') NOT NULL,
cust_ID integer NOT NULL,
Constraint debit_card_pk primary key(acct_no,exp_date)
);
DROP TABLE IF EXISTS DEBIT_CARD;
Create Table DEBIT_CARD(
acct_no Char(16),
exp_date date,
bank_no CHAR(9) NOT NULL,
Constraint debit_card_pk primary key(acct_no,exp_date),
Constraint debit_card_fk foreign key(acct_no,exp_date) References card_account(Acct_no,exp_date)
ON UPDATE CASCADE
ON DELETE CASCADE
);
Related
I keep getting this error when attempting to create a table with SQL.
I have these two tables:
I'm using PHPMyAdmin and it won't allow me to use M_id as a foreign key which references Employee Table primary key E_id.
Anyone able to see what's wrong with my code?
Thanks!
Foreign key definitions have to exactly match the primary key columns to which they refer. In this case, you defined Department.M_id to a be a nullable integer column, while EMPLOYEE.E_id is integer not nullable. Try making M_id not nullable:
CREATE TABLE Department (
D_name VARCHAR(100) NOT NULL,
D_id INT NOT NULL,
M_id INT NOT NULL DEFAULT 0000,
...
FOREIGN KEY (M_id) REFERENCES EMPLOYEE(E_id)
ON DELETE SET DEFAULT ON UPDATE CASCADE
)
Your code has multiple errors:
varchar() length is too long.
You have a forward reference for a foreign key constraint.
SET DEFAULT doesn't really work.
You want something like this:
CREATE TABLE employees (
employee_id int not null primary key,
Job_type VARCHAR(100),
Ssn INT NOT NULL,
Salary DECIMAL NOT NULL,
Address VARCHAR(500) NOT NULL,
First_name VARCHAR(50) NOT NULL,
M_initial CHAR(1),
Last_name VARCHAR(50) NOT NULL,
E_end_date DATE,
E_start_date DATE NOT NULL,
department_id INT NOT NULL,
Super_id INT,
FOREIGN KEY (Super_id) REFERENCES employees(employee_id) ON DELETE SET NULL ON UPDATE CASCADE,
UNIQUE (Ssn)
);
CREATE TABLE departments (
department_id int primary key,
D_name VARCHAR(100) NOT NULL,
D_id INT NOT NULL,
M_id INT DEFAULT 0000,
Manager_start_date DATE NOT NULL,
Manager_end_date DATE,
Report VARCHAR(8000),
Num_of_employees INT NOT NULL,
FOREIGN KEY (M_id) REFERENCES employees(employee_id) ON DELETE SET NULL ON UPDATE CASCADE,
UNIQUE (D_name)
);
ALTER TABLE employees ADD CONSTRAINT FOREIGN KEY (department_id) REFERENCES departments(department_id)
ON DELETE CASCADE ON UPDATE CASCADE;
I also changed a few other things:
The table names are plural.
The primary keys are the singular form followed by "_id".
Foreign keys and primary keys have the same name.
The primary key is the first column in the table.
Here is a db<>fiddle showing that this works.
I will not question your design, though it looks problematic.
However - You cannot reference a table which doesn't exist yet (REFERENCES Department(D_id)). You should either remove the FOREIGN KEY constraints from the CREATE statements and add them afterwards in ALTER TABLE statements.
Example:
CREATE TABLE EMPLOYEE (...);
CREATE TABLE Department (...);
ALTER TABLE EMPLOYEE
ADD FOREIGN KEY (D_id)
REFERENCES Department(D_id)
ON DELETE CASCADE
ON UPDATE CASCADE
;
Demo
Or temporarily disable foreign key checks:
SET FOREIGN_KEY_CHECKS = 0;
CREATE TABLE EMPLOYEE (...);
CREATE TABLE Department (...);
SET FOREIGN_KEY_CHECKS = 1;
Demo
You can also not use ON DELETE SET DEFAULT. InnoDB doesn't support it. You need to change it to ON DELETE SET NULL. If you want that behavior, you will need to implement it either in your application code or in a trigger.
I would also use TEXT as data type instead of VARCHAR(30000).
Hi I'm not very familiar with MySQL as I have only started using it today and I keep getting this syntax error and am not really sure what the problem is. I have attached a screenshot of the code and also pasted it below with the error in bold.
I'm sorry if this is a silly error that is easily fixed I'm just not sure how to fix it and would be very appreciative of any help.
CREATE TABLE copy (
`code` INT NOT NULL,
isbn CHAR(17) NOT NULL,
duration TINYINT NOT NULL,
CONSTRAINT pkcopy PRIMARY KEY (isbn, `code`),
CONSTRAINT fkcopy FOREIGN KEY (isbn) REFERENCES book (isbn));
CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pkstudent PRIMARY KEY (`no`));
CREATE TABLE loan (
`code` INT NOT NULL,
`no` INT NOT NULL,
taken DATE NOT NULL,
due DATE NOT NULL,
`return` DATE NULL,
CONSTRAINT pkloan PRIMARY KEY (taken, `code`, `no`),
CONSTRAINT fkloan FOREIGN KEY (`code`, `no`) REFERENCES copy, student **(**`code`, `no`));
Create the tables first, then use the ALTER TABLE statement to add the foreign keys one by one. You won't be able to call two different tables on the foreign key, so you'll have to use an ID that maps to both. Here is an example to add the foreign keys after the table has been created:
Add a new table named vendors and change the products table to include the vendor id field:
USE dbdemo;
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
When trying to create the foreign keys on the last table I get the error "cannot add foreign key constraint" -
create database library_PW;
use library_PW;
create table title(
title_id varchar(20)primary key,
name varchar(50)not null,
reservation_no numeric(10),
lending_time varchar(15));
create table item(
title_id varchar(20)not null,
item_id varchar(20)not null,
constraint pk_item primary key(title_id,item_id));
create table magazine(
mag_id varchar(20)not null,
mag_date varchar(15)not null,
constraint pk_magazine primary key(mag_id,mag_date));
create table book(
ISBN varchar(20)primary key,
date_added date not null);
create table author(
author_id varchar(20)primary key,
author_name varchar(30)not null);
create table book_author(
ISBN varchar(20),
author_id varchar(20),
index (ISBN),
index (author_id),
constraint pk_book_author primary key(ISBN,author_id),
constraint fk_ISBNCode foreign key (ISBN) references book(ISBN),
constraint fk_authorcode foreign key (author_id) references author(author_id));
create table borrower(
membership_id varchar(20)primary key,
name varchar(20)not null,
address varchar(60)not null,
dob date not null,
date_joined date not null,
telephone numeric(12),
email varchar(30));
create table reservation(
title_id varchar(20),
membership_id varchar(20),
reserve_date varchar(20),
index (title_id),
index (membership_id),
constraint pk_reservation primary key(title_id, membership_id,reserve_date),
constraint fk_title foreign key(title_id) references title(title_id),
constraint fk_mem_id foreign key(membership_id) references borrower(membership_id));
create table loan(
title_id varchar(20),
item_id varchar(20),
borrower_date varchar(20),
index (title_id),
index (item_id),
constraint pk_reservation primary key(title_id,item_id,borrower_date),
constraint fk_loantitle foreign key(title_id) references title(title_id),
constraint fk_loanitem foreign key(item_id) references item(item_id));
Thanks in advance!
When I run into this issue, its always because I choose the wrong type data type.. The data type for the child column must match the parent column exactly.
Example: table.key = int & table.child=vchar
For me, its always that! Hope that helps.
Thanks all! It wasn't the data type (for once), it was the problem with the table item as suggested, and SHOW ENGINE INNODB STATUS\G pointed me to the answer.
All that was wrong was in the table item I should have had item_id before title_id.
Thanks again.
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 am trying to add records into two tables below,
CREATE TABLE customer
(Custno CHAR(3),
Custname VARCHAR(25) NOT NULL,
Custstreet VARCHAR(30) NOT NULL,
Custcity VARCHAR(15) NOT NULL,
Custprov VARCHAR(3) NOT NULL,
Custpcode VARCHAR(6) NOT NULL,
Disc DECIMAL(3,1),
Balance DECIMAL(7,2),
Credlimit DECIMAL(5),
Srepno CHAR(3),
CONSTRAINT pkcustno PRIMARY KEY (Custno),
CONSTRAINT fksrepno FOREIGN KEY (Srepno) REFERENCES salesrep(Srepno)
);
CREATE TABLE orders
(Orderno CHAR(5) UNIQUE NOT NULL,
Orderdate DATE,
Custno CHAR(3) NOT NULL,
CONSTRAINT fkordercust FOREIGN KEY (Custno) REFERENCES customer (Custno)
);
When adding like this,
INSERT INTO orders(Orderno, Orderdate, Custno) VALUES('14587','2011-11-09', '125' );
INSERT INTO orders(Orderno, Orderdate, Custno) VALUES('11547','2011-11-07', '125' );
I get, "Cannot add or update a child row: a foreign key constraint fails (sh.orders, CONSTRAINT fkordercust FOREIGN KEY (Custno) REFERENCES customer (Custno))
"
Is something wrong the table?
You do not have a customer with CustNo = '125'. Because of this, the Foreign key fails. You are trying to place an order for a non-existent customer, the DB throws an error.
Do you actually have a customer row for customer number 125? I think not. The error message is telling you exactly what's wrong.
The foreign key constraint which ensures that no orders can be created for non-existent customers is being violated:
CONSTRAINT fkordercust FOREIGN KEY (Custno) REFERENCES customer (Custno)
Create the customer row first then you can add order rows for that customer to your heart's content.
Your table is fine, you just don't have a customer with a CustNo of '125' in the database.
You have created a foreign key to the customer table, but ( apparently ) inserted no data into it.
Do you have a customer with a number of 125?