I used a script to make a tables within the same database. Once both tables were made, I made a seperate script to insert a set of values in the table, however with one of the scripts it doesnt seem to insert any data into the table, but comes up with the error.
These are my tables;
CREATE TABLE IF NOT EXISTS customers(
customer_id INT UNSIGNED NOT NULL,
first_name VARCHAR(20) NOT NULL,
middle_name VARCHAR(20),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
password VARCHAR(40) NOT NULL,
dob DATETIME NOT NULL,
address_line VARCHAR(40) NOT NULL,
postcode VARCHAR(20) NOT NULL,
PRIMARY KEY(customer_id),
FOREIGN KEY(postcode) REFERENCE postcodes(postcode)
);
In a seperate script,
CREATE TABLE IF NOT EXISTS postcodes(
postcode VARCHAR(20) NOT NULL,
address_line_2 VARCHAR(20),
city VARCHAR(40) NOT NULL,
PRIMARY KEY(postcode)
);
The scripts to insert data into the tables are here.
This one works without any errors and successfully populates the table.
INSERT INTO postcodes(postcode,address_line_2,city)
Values
('DH1 568','Forest Lane','Durham'),
('DH1 679','Dry Wood','Durham'),
('DH1 4AS','North Of the Wall','Westeros'),
('DH1 4LA',"Snoop's Crib",'Durham');
And this is the one which comes up with an error message,
INSERT INTO customers(customer_id,first_name,postcode)
values
('1','Zaak','DH1 568'),
('2','Matt','DH1 679'),
('3','Jon','DH1 4AS'),
('4','Zak','DH1 4LA'),
('5','Gaz','DH1 7SO');
The error message which appears is,
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`hardware_store`.`customers`, CONSTRAINT `customers_ibfk_1` FOREIGN KEY (`postcode`) REFER
ENCES `postcodes` (`postcode`))
You have a foreign key constraint specifying that customers(postcode) refers to a valid postal code in the postcodes table.
Then, you try to insert 'DH1 7SO' and it doesn't work because this postcode is not in postcodes.
This is how foreign key references work. The database is working exactly as it should and doing exactly what you instructed it to do.
If you want the valid rows to be inserted and the invalid ones ignored, then use the IGNORE option on INSERT (see here).
Related
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;
I am new to creating/testing/working with MySQL.
In this I have created a database and have used the command to USE the Database, however when trying to create a table, Error Code:1064 keeps coming up.
I have no previous tables in this database, this would be the first table.
I am unsure where the error is and would greatly appreciate it if someone could help me identiy the error and the reason why?
CREATE TABLE Customers(
customerNumber INT NOT NULL,
firstName VARCHAR(60),
lastName VARCHAR(60),
address VARCHAR(50) NOT NULL,
city VARCHAR(20) NOT NULL,
state ENUM('QLD','VIC','NSW','WA','TAS','NT','SA') NOT NULL,
postCode INT(4) NOT NULL,
region VARCHAR(60),
email VARCHAR(254),
PRIMARY KEY(customerNumber),
FOREIGN KEY(customerNumber)
);
A foreign key must reference another table.
The other table must exist before you can reference it in a foreign key.
I contributed to a checklist for foreign keys in this post:
https://stackoverflow.com/a/4673775/20860
I'm new to SQL so I'm likely asking a question with a very obvious answer. I'm making a simple database for phone plans, my tables, in order, are:
COUNTRY, PROVIDER, PHONE, PLAN, CUSTOMER.
They all have one primary key, and except for COUNTRY all have foreign keys referencing to the previous table.
My issue arises when inserting values into the PHONE table. These are the PROVIDER and PHONE tables:
CREATE TABLE Provider_T(
Name VARCHAR(25),
Provider_ID CHAR(10) NOT NULL,
Country_Abbrev CHAR(3) DEFAULT NULL,
Website VARCHAR(50) DEFAULT NULL,
CService_Number VARCHAR(15) DEFAULT NULL,
CONSTRAINT Provider_T_PK PRIMARY KEY(Provider_ID),
CONSTRAINT Country_Abbrev_FK FOREIGN KEY(Country_Abbrev) REFERENCES Country_T(Abbreviation));
CREATE TABLE Phone_T(
Phone_Model VARCHAR(25) NOT NULL,
Provider_ID CHAR(3) NOT NULL,
Smartphone BOOLEAN,
CONSTRAINT Phone_Model_PK PRIMARY KEY(Phone_Model),
CONSTRAINT Provider_ID_FK FOREIGN KEY(Provider_ID) REFERENCES Provider_T(Provider_ID));
This is my insert for the PHONE table:
INSERT INTO Phone_T(Phone_Model, Provider_ID, Smartphone) VALUES ("Nexus 5", "ROG", TRUE);
INSERT INTO Phone_T(Phone_Model, Provider_ID, Smartphone) VALUES ("Nexus 5", "KOD", TRUE);
I know I have duplicate Primary Keys, I'm stumped on how I could make one Phone Model for multiple PROVIDERS. I would love some advice and any help is appreciated.
I've got a problem with an RIM I have to write from scratch for school.
The thing is, any syntax checker I use doesn't give me any helpul clues.
create database FullHouseGr1;
use FullHouseGr1;
create table Player
(player_id int not null,
first_name varchar(20) not null,
surname varchar(20) not null,
addres varchar(40) not null,
postal_code varchar(6) not null,
place varchar(40) not null,
phone_number varchar(20) not null,
email_addres varchar(255) not null,
points int not null,
primary key(player_id));
the error is near create table Player at line 2.
edit: It is working in MYSQL workbench, but not in online syntax checkers.
snip -
After creating the database, and before creating any tables, you need to tell MySQL where you want those tables created.
USE FullHouseGr1;
Second, int() is not a valid column type. You can just use INT (or INT(10), or whatever number you need).
Finally, your ON DELETE SET NULL and ON UPDATE cascade statements. They cannot be on their own, they are part of FOREIGN KEY definitions.
FOREIGN KEY(date_time) REFERENCES Event ON DELETE no action ON UPDATE cascade
Notice how that's all one line (without commas). In a CREATE TABLE command, you separate definitions with commas. ON DELETE SET NULL must be part of a FOREIGN KEY definitions, it's not its own definition.
So I don't understand why I cannot insert data in my table that have foreign constraint keys or even modify anything in it.
Here is an example of the tables that are created. I am trying to insert data in the addresses table:
///////////////////////ADDRESSES TABLE ////////////////////////
CREATE TABLE IF NOT EXISTS addresses (
id INT NOT NULL AUTO_INCREMENT,
addressline1 VARCHAR(255) NOT NULL,
addressline2 VARCHAR(255) NOT NULL,
postcode VARCHAR(255) NOT NULL,
phonenumber INT(13) NOT NULL,
country_id INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (country_id) REFERENCES countries(id)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ENGINE=InnoDB ";
///////////////////////COUNTRIES TABLE ////////////////////////
CREATE TABLE IF NOT EXISTS countries (
id INT NOT NULL AUTO_INCREMENT,
countryname VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
)
The issue here is that you are trying to insert into a referencing table (addresses) when the referenced entry (the country you reference) does not exist. That's what's triggering the FOREIGN KEY CONSTRAINT exception.
Try first inserting some countries into the countries table, then inserting some addresses where you reference those countries you entered in the first step.
As for your second question, that's a choice for you to make. I would probably choose to have the User have an Address (address field in the User table), but some of that depends on how the data is being used/updated.
Have a quick look through this resource if you're new to relational database design. It covers (in brief) topics like relationship types, key constraints, and normal forms.