The conflict occurred in database " - mysql

I have the code here, but it was written by my teachers
create database abc_quanlybanhang111111;
use abc_quanlybanhang111111;
create table abc_nhacc
(
MaCC1 varchar(10) primary key,
TenNhaCC varchar(50) not null,
DiaChiCC varchar(50),
PhoneCC varchar(11),
);
create table abc_mamh
(
MaMH1 varchar(50) primary key,
TenMH varchar(100),
DonGia int,
SoLuong int,
MaCC1 varchar(10) foreign key references abc_nhacc(MaCC1)
);
create table abc_khachhang
(
MaMh1 VARCHAR(10) PRIMARY KEY,
TenKh varchar(50),
DiaChi varchar(50),
SĐT int,
);
CREATE TABLE abc_donhang
(
MaDH1 varchar(10) primary key,
NgayDH DATE default GetDate(),
MaKH1 varchar(10) foreign key references abc_khachhang(MaMH1)
);
create table abc_chitietdonhang
(
MaDH1 varchar(10) foreign key references abc_donhang(MaDH1) ,
MaMH1 varchar(50) foreign key references abc_mamh(MaMH1),
SoLuong int check (soluong>0)
constraint pk_dmhh primary key ( MaDH1, MaMH1)
);
insert into abc_nhacc
values
('K001', 'THE GIOI DI DONG', '121 TRAN QUANG KHAI', '0164789720'),
('K002', 'NGUYEN KIM', '12 TRAN PHU', '0161792793'),
('K003', 'THIEN HOA', '2 BA HUYEN THANH QUAN', '094850873'),
('K004', 'PHONG VU', '32 LE VAN VIET QUAN 9', '85839201'),
('K005', 'TAN BINH', '14 NGUYEN THI DINH', '0912012901')
SELECT *
FROM abc_nhacc;
insert into abc_mamh
values
('S001', 'MSI ACER GAMING', 2000000, 1, 'K001');
insert into abc_mamh
values
('S002', 'MSI ASUS GAMING', 1000000, 10, 'K002'),
('S003', 'MSI GAMING', 1100000, 1, 'K003'),
('S004', 'LENOVO GAMING', 2000, 111, 'K004'),
('S005', 'IPHONE', 120000, 1, 'K005')
SELECT *
FROM abc_mamh;
insert into abc_khachhang
values
('KH1', 'LONG NGUYEN', '12 TRAN QUANG DIEU QUAN 1', '0938078972');
insert into abc_khachhang
values
('KH2', 'THONG NGUYEN', '1 TRAN DIEU QUAN 2', '0968071972'),
('KH3', 'THANH NGUYEN', '23 NGUYEN THI DINH QUAN 8', '0138073972'),
('KH4', 'THINH NGUYEN', '1 TRUONG DINH QUAN 1', '016479828'),
('KH5', 'LINH TRAN', '2 TRAN QUANG KHAI QUAN 1', '0938078122')
SELECT *
FROM abc_mamh;
insert into abc_chitietdonhang
values('DH001', 'MH001', 2),
('DH002', 'MH002', 3),
('DH003', 'MH003', 1),
('DH004', 'MH004', 9),
('DH004', 'MH005', 4),
('DH003', 'MH006', 11),
('DH001', 'MH007', 12);
I have try to fix the code with the step delete the foreign key but it always show errors after I delete it :
Msg 547, Level 16, State 0, Line 72
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__abc_chiti__MaDH1__4222D4EF". The conflict occurred in database "abc_quanlybanhang1111111", table "dbo.abc_donhang", column 'MaDH1'
Please help me learn how to can fix this errors. Thank.

You have to add the rows in abc_donhang which you are trying to reference in your insert into abc_chitietdonhang ... query. You try to reference the row with the Id DH001, but it doesn't exists (yet). Same goes for the Id MH001, it doesn't exists in the abc_mamh table either.

Related

sql integrity constraint parent key not found

I am trying to do something so simple creating and insert 4 tables with their data. I have spent hours on the web researching integrity constraints and tried several IDE's in case there's a bug but nothing seems to work. Code is shows below (excuted in order).
I can insert the data for the first two tables i.e vod_actor and vod_classification but when trying to add third/fourth table data I get the following error:
ORA-02291: integrity constraint (SYSTEM.VOD_FILM_CLASS_FK) violated - parent
I don't understand why because the FK for vod_film is the PK for vod_classification which already has its data populated.
Any help would be greatly appreciated. I am a beginner please bear that in mind. Thanks
CREATE TABLE vod_actor (
dbActorId CHAR(4) NOT NULL,
dbFirstname VARCHAR2(50) NOT NULL,
dbLastname VARCHAR2(50) NOT NULL,
dbDateOfBirth DATE,
dbNationality VARCHAR2(30),
dbBiography CLOB,
CONSTRAINT vod_actor_PK PRIMARY KEY (dbActorId)
);
CREATE TABLE vod_classification (
dbClassId CHAR(4) NOT NULL,
dbDescription VARCHAR(250) NOT NULL,
CONSTRAINT vod_classification_PK PRIMARY KEY (dbClassId)
);
CREATE TABLE vod_film (
dbFilmId CHAR(4) NOT NULL,
dbTitle VARCHAR2(100) NOT NULL,
dbDirector_firstname VARCHAR2(50) NOT NULL,
dbDirector_lastname VARCHAR2(50) NOT NULL,
dbGenre VARCHAR2(20),
dbUK_release_date DATE,
dbFilename VARCHAR2(50),
dbRuntime NUMBER(4),
dbClass CHAR(3),
CONSTRAINT vod_film_PK PRIMARY KEY (dbFIlmId),
CONSTRAINT vod_film_class_FK FOREIGN KEY (dbClass) REFERENCES
vod_classification (dbClassId) ON DELETE SET NULL
);
CREATE TABLE vod_role (
dbFilmId Char(4) NOT NULL,
dbActorId CHAR(4) NOT NULL,
dbCharacterName VARCHAR2(25) NOT NULL,
dbFirstAppearance NUMBER(6),
dbDescription CLOB,
CONSTRAINT vod_role_PK PRIMARY KEY (dbFilmId, dbActorId, dbCharacterName),
CONSTRAINT vod_role_film_FK FOREIGN KEY (dbFilmId) REFERENCES vod_film (dbFilmId)
ON DELETE CASCADE,
CONSTRAINT vod_role_actor_FK FOREIGN KEY (dbActorId) REFERENCES vod_actor (dbActorId)
ON DELETE CASCADE
);
//Insert into vod_actor & vod_classification works fine
Executing code below gives the error:
INSERT INTO vod_film VALUES ('1', 'Toy Story 3', 'Lee', 'Unkrich', 'Comedy', '19-JUL-2010', 'ToyStory3.mpg', '103', 'U');
INSERT INTO vod_film VALUES ('2', 'Lord of the Rings: Fellowship of the ring', 'Peter', 'Jackson', 'Fantasy', '19-DEC-2001', 'Fellowship.mpg', '178', '12');
INSERT INTO vod_film VALUES ('3', 'Lord of the Rings: Two Towers', 'Peter', 'Jackson', 'Fantasy', '18-DEC-2002', 'TwoTowers.mpg', '179', '12');
INSERT INTO vod_film VALUES ('4', 'Lord of the Rings: Return of the King', 'Peter', 'Jackson', 'Fantasy', '17-DEC-2003', 'KingReturns.mpg', '201', '12');
INSERT INTO vod_film VALUES ('5', 'Face/Off', 'John', 'Woo', 'Action', '7-NOV-1997', 'FaceOff.mpg', '138', '18');
INSERT INTO vod_film VALUES ('6', 'The Nutty Professor', 'Tom', 'Shadyac', 'Comedy', '4-OCT-1996', 'NuttyProf.mpg', '95', '12');
So in this case different character lengths for the PK FK fields I think is the issue.
CREATE TABLE vod_classification (
dbClassId CHAR(4) NOT NULL,
....
CREATE TABLE vod_film (
...
dbClass CHAR(3),
Given constraint
CONSTRAINT vod_film_class_FK FOREIGN KEY (dbClass) REFERENCES
vod_classification (dbClassId)
Appear to be the issue. char(3) <> char(4) make them both the same. likely the 3 to 4.
If I remember right char pads spaces to the end so 'U ' will never equal 'U ' U w/ 2 spaces for 3 characters vs U with 3 spaces for 4 characters. One of the reasons I prefer varchar no padding of spaces. Why was char chosen here?

MySQL 5.6 Foreign Key Error Message

I am getting this error when I try to run this bit of code in SQLFiddle. It is using MySQL 5.6.
Cannot add or update a child row: a foreign key constraint fails (db_9_f9acae.order_items, CONSTRAINT order_items_ibfk_1 FOREIGN KEY (Donut_Order_ID) REFERENCES custorder (Donut_Order_ID))
My code looks like this:
CREATE TABLE Customer (
Customer_ID INTEGER PRIMARY KEY AUTO_INCREMENT,
CustFirstName VARCHAR(50) NOT NULL,
CustLastName VARCHAR(50) NOT NULL,
Address VARCHAR(50) NOT NULL,
AptNum VARCHAR(50),
City VARCHAR(50) NOT NULL,
State VARCHAR(13) NOT NULL,
Zip VARCHAR(15) NOT NULL,
HomePhn VARCHAR(20),
MobPhn VARCHAR(20),
OthPhn VARCHAR(20)
);
CREATE TABLE Donut (
Donut_ID INTEGER PRIMARY KEY,
Donut_Name VARCHAR(255) NOT NULL,
Donut_Description VARCHAR(255) NOT NULL,
Donut_Price FLOAT NOT NULL
);
CREATE TABLE CustOrder (
Donut_Order_ID INTEGER PRIMARY KEY,
Date DATE NOT NULL,
Notes VARCHAR(255) NOT NULL,
Customer_ID INTEGER,
FOREIGN KEY (Customer_ID) REFERENCES Customer (Customer_ID)
);
CREATE TABLE Order_Items (
Donut_Order_ID INTEGER NOT NULL,
Donut_ID INTEGER NOT NULL,
Qty INTEGER NOT NULL,
PRIMARY KEY (Donut_Order_ID, Donut_ID),
FOREIGN KEY (Donut_Order_ID) REFERENCES CustOrder (Donut_Order_ID),
FOREIGN KEY (Donut_ID) REFERENCES Donut (Donut_ID)
);
CREATE VIEW CustInfo AS
SELECT CONCAT(CustFirstName,' ', CustLastName) AS CustFullName,
Customer_ID,
Address,
AptNum,
City,
State,
Zip,
HomePhn,
MobPhn,
OthPhn
FROM Customer;
CREATE INDEX DonutIndex ON Donut (Donut_Name);
INSERT INTO Customer VALUES
(1, "John", "Glenn", 1, NULL, "Kennedy Space Center", "FL", "32899", "(321) 867-5000", NULL, NULL),
(2, "Theodore", "Von Karman", "4800 Oak Dr", "Jet Propulsion Laboratory", "Pasadena", "CA", "91109", "(818) 354-4321", NULL, NULL),
(3, "Margaret", "Hamilton", "555 Technology Square", "Charles Stark Draper Laboratory", "Cambridge", "MA", "02139", "(617) 258-1000", "(123)456-7890", NULL);
INSERT INTO Donut
VALUES
(1, 'Plain' , 'Plain Donut' , 1.50),
(2, 'Glazed' , 'Glazed Donut' , 1.75),
(3, 'Cinnamon' , 'Cinnamon Donut' , 1.75),
(4, 'Chocolate' , 'Chocolate Donut' , 1.75),
(5, 'Sprinkle' , 'Sprinkle Donut' , 1.75),
(6, 'Gluten-Free' , 'Gluten-Free Donut' , 2.00);
INSERT INTO Order_Items VALUES
(2 , 4 , 3),
(3, 2, 1);
INSERT INTO CustOrder VALUES
('1', '11-24-2017', NULL, '1'),
('2', '11-25-2017', NULL, '2');
This is my first time working with anything SQL related and have tried referring to the MySQL docs, but don't know what I'm doing wrong. The error does not appear until after the bottom 2 INSERT INTO statements are added. Any help would be greatly appreciated.
You are getting this error because you are trying to insert data set in table whose references are missing in referenced table for example in Order_Items you are trying to link custorder table with Donut_Order_ID 2 and 3 but it is empty
So first fill your custorder and then link with your table
INSERT INTO CustOrder VALUES
('1', '11-24-2017', NULL, '1'),
('2', '11-25-2017', NULL, '2');
INSERT INTO Order_Items VALUES
(2 , 4 , 3),
(3, 2, 1);
Also i see there is no reference present in CustOrder for Donut_Order_ID = 3 but in Order_Items data you have trying to link with this missing reference which will again give you error
demo

Trying to perform an insert into

Been trying to perform an insert into command for a table called customers. However whenever I try to do a query I get the following error.
Error Code: 1364. Field 'customer_address' doesn't have a default value 0.000 sec
I'm not entirely sure how I would go about setting a default value. Any suggestions?
lock table customers write;
set foreign_key_checks = 0;
alter table customers modify customer_id integer auto_increment;
insert into customers (customer_first_name, customer_last_name)
values ("Nathan", "Rivera"),
("thom", "something");
Here is the script used to create my table
-- *************************************************************
-- This script creates the database
-- **REVISED by PRP to remove some orders
-- **REVISED by PRP to add artist table
-- **REVISED by PRP to link employee table to orders
-- *************************************************************
DROP TABLE IF EXISTS customers;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS order_details;
DROP TABLE IF EXISTS items;
DROP TABLE IF EXISTS artists;
DROP TABLE IF EXISTS employees;
-- create tables
CREATE TABLE customers
(
customer_id INT ,
customer_first_name VARCHAR(20),
customer_last_name VARCHAR(20) NOT NULL,
customer_address VARCHAR(50) NOT NULL,
customer_city VARCHAR(20) NOT NULL,
customer_state CHAR(2) NOT NULL,
customer_zip CHAR(5) NOT NULL,
customer_phone CHAR(10) NOT NULL,
customer_fax CHAR(10),
CONSTRAINT customers_pk
PRIMARY KEY (customer_id)
);
CREATE TABLE artists
(
artist_id INT NOT NULL,
artist_name VARCHAR(30),
CONSTRAINT artist_pk
PRIMARY KEY (artist_id)
);
CREATE TABLE items
(
item_id INT NOT NULL,
title VARCHAR(50) NOT NULL,
artist_id INT NOT NULL,
unit_price DECIMAL(9,2) NOT NULL,
CONSTRAINT items_pk
PRIMARY KEY (item_id),
CONSTRAINT items_fk_artists
FOREIGN KEY (artist_id) REFERENCES artists (artist_id)
);
CREATE TABLE employees
(
employee_id INT NOT NULL,
last_name VARCHAR(20) NOT NULL,
first_name VARCHAR(20) NOT NULL,
manager_id INT
,
CONSTRAINT employees_pk
PRIMARY KEY (employee_id),
CONSTRAINT emp_fk_mgr FOREIGN KEY (manager_id) REFERENCES employees(employee_id) );
CREATE TABLE orders
(
order_id INT NOT NULL,
customer_id INT NOT NULL,
order_date DATE NOT NULL,
shipped_date DATE,
employee_id INT,
CONSTRAINT orders_pk
PRIMARY KEY (order_id),
CONSTRAINT orders_fk_customers
FOREIGN KEY (customer_id) REFERENCES customers (customer_id),
CONSTRAINT orders_fk_employees
FOREIGN KEY (employee_id) REFERENCES employees (employee_id)
);
CREATE TABLE order_details
(
order_id INT NOT NULL,
item_id INT NOT NULL,
order_qty INT NOT NULL,
CONSTRAINT order_details_pk
PRIMARY KEY (order_id, item_id),
CONSTRAINT order_details_fk_orders
FOREIGN KEY (order_id)
REFERENCES orders (order_id),
CONSTRAINT order_details_fk_items
FOREIGN KEY (item_id)
REFERENCES items (item_id)
);
-- insert rows into tables
INSERT INTO customers VALUES
(1,'Korah','Blanca','1555 W Lane Ave','Columbus','OH','43221','6145554435','6145553928'),
(2,'Yash','Randall','11 E Rancho Madera Rd','Madison','WI','53707','2095551205','2095552262'),
(3,'Johnathon','Millerton','60 Madison Ave','New York','NY','10010','2125554800',NULL),
(4,'Mikayla','Davis','2021 K Street Nw','Washington','DC','20006','2025555561',NULL),
(5,'Kendall','Mayte','4775 E Miami River Rd','Cleves','OH','45002','5135553043',NULL),
(6,'Kaitlin','Hostlery','3250 Spring Grove Ave','Cincinnati','OH','45225','8005551957','8005552826'),
(7,'Derek','Chaddick','9022 E Merchant Wy','Fairfield','IA','52556','5155556130',NULL),
(8,'Deborah','Davis','415 E Olive Ave','Fresno','CA','93728','5595558060',NULL),
(9,'Karina','Lacy','882 W Easton Wy','Los Angeles','CA','90084','8005557000',NULL),
(10,'Kurt','Nickalus','28210 N Avenue Stanford','Valencia','CA','91355','8055550584','055556689'),
(11,'Kelsey','Eulalia','7833 N Ridge Rd','Sacramento','CA','95887','2095557500','2095551302'),
(12,'Anders','Rohansen','12345 E 67th Ave NW','Takoma Park','MD','24512','3385556772',NULL),
(13,'Thalia','Neftaly','2508 W Shaw Ave','Fresno','CA','93711','5595556245',NULL),
(14,'Gonzalo','Keeton','12 Daniel Road','Fairfield','NJ','07004','2015559742',NULL),
(15,'Ania','Irvin','1099 N Farcourt St','Orange','CA','92807','7145559000',NULL),
(16,'Dakota','Baylee','1033 N Sycamore Ave.','Los Angeles','CA','90038','2135554322',NULL),
(17,'Samuel','Jacobsen','3433 E Widget Ave','Palo Alto','CA','92711','4155553434',NULL),
(18,'Justin','Javen','828 S Broadway','Tarrytown','NY','10591','8005550037',NULL),
(19,'Kyle','Marissa','789 E Mercy Ave','Phoenix','AZ','85038','9475553900',NULL),
(20,'Erick','Kaleigh','Five Lakepointe Plaza, Ste 500','Charlotte','NC','28217','7045553500',NULL),
(21,'Marvin','Quintin','2677 Industrial Circle Dr','Columbus','OH','43260','6145558600','6145557580'),
(22,'Rashad','Holbrooke','3467 W Shaw Ave #103','Fresno','CA','93711','5595558625','5595558495'),
(23,'Trisha','Anum','627 Aviation Way','Manhatttan Beach','CA','90266','3105552732',NULL),
(24,'Julian','Carson','372 San Quentin','San Francisco','CA','94161','6175550700',NULL),
(25,'Kirsten','Story','2401 Wisconsin Ave NW','Washington','DC','20559','2065559115',NULL);
INSERT INTO artists(artist_id,artist_name) VALUES
(10, 'Umani'),
(11, 'The Ubernerds'),
(12, 'No Rest For The Weary'),
(13, 'Burt Ruggles'),
(14, 'Sewed the Vest Pocket'),
(15, 'Jess & Odie'),
(16, 'Onn & Onn');
INSERT INTO items (item_id,title,artist_id,unit_price) VALUES
(1,'Umami In Concert',10,17.95),
(2,'Race Car Sounds',11,13),
(3,'No Rest For The Weary',12,16.95),
(4,'More Songs About Structures and Comestibles',12,17.95),
(5,'On The Road With Burt Ruggles',13,17.5),
(6,'No Fixed Address',14,16.95),
(7,'Rude Noises',15,13),
(8,'Burt Ruggles: An Intimate Portrait',13,17.95),
(9,'Zone Out With Umami',10,16.95),
(10,'Etcetera',16,17);
INSERT INTO employees VALUES
(1,'Smith', 'Cindy', null),
(2,'Jones', 'Elmer', 1),
(3,'Simonian', 'Ralph', 2),
(9,'Locario', 'Paulo',1),
(8,'Leary', 'Rhea',9),
(4,'Hernandez','Olivia',9),
(5,'Aaronsen', 'Robert',4),
(6,'Watson', 'Denise',8),
(7,'Hardy', 'Thomas',2);
INSERT INTO orders VALUES
(19, 1, '2012-10-23', '2012-10-28', 6),
(29, 8, '2012-11-05', '2012-11-11', 6),
(32, 11, '2012-11-10', '2012-11-13', NULL),
(45, 2, '2012-11-25', '2012-11-30', NULL),
(70, 10, '2012-12-28', '2013-01-07', 5),
(89, 22, '2013-01-20', '2013-01-22', 7),
(97, 20, '2013-01-29', '2013-02-02', 5),
(118, 3, '2013-02-24', '2013-02-28', 7),
(144, 17, '2013-03-21', '2013-03-29', NULL),
(158, 9, '2013-04-04', '2013-04-20', NULL),
(165, 14, '2013-04-11', '2013-04-13', NULL),
(180, 24, '2013-04-25', '2013-05-30', NULL),
(231, 15, '2013-06-14', '2013-06-22', NULL),
(242, 23, '2013-06-24', '2013-07-06', 3),
(264, 9, '2013-07-15', '2013-07-18', 6),
(298, 18, '2013-08-18', '2013-09-22', 3),
(321, 2, '2013-09-09', '2013-10-05', 6),
(381, 7, '2013-11-08', '2013-11-16', 7),
(413, 17, '2013-12-05', '2014-01-11', 7),
(442, 5, '2013-12-28', '2014-01-03', 5),
(479, 1, '2014-01-30', '2014-03-03', 3),
(491, 16, '2014-02-08', '2014-02-14', 5),
(523, 3, '2014-03-07', '2014-03-15', 3),
(548, 2, '2014-03-22', '2014-04-18', NULL),
(550, 17, '2014-03-23', '2014-04-03', NULL),
(601, 16, '2014-04-21', '2014-04-27', NULL),
(607, 20, '2014-04-25', '2014-05-04', NULL),
(624, 2, '2014-05-04', '2014-05-09', NULL),
(627, 17, '2014-05-05', '2014-05-10', NULL),
(630, 20, '2014-05-08', '2014-05-18', 7),
(651, 12, '2014-05-19', '2014-06-02', 7),
(658, 12, '2014-05-23', '2014-06-02', 7),
(687, 17, '2014-06-05', '2014-06-08', NULL),
(693, 9, '2014-06-07', '2014-06-19', NULL),
(703, 19, '2014-06-12', '2014-06-19', 7),
(778, 13, '2014-07-12', '2014-07-21', 7),
(796, 17, '2014-07-19', '2014-07-26', 5),
(800, 19, '2014-07-21', '2014-07-28', NULL),
(802, 2, '2014-07-21', '2014-07-31', NULL),
(824, 1, '2014-08-01', NULL, NULL),
(827, 18, '2014-08-02', NULL, NULL),
(829, 9, '2014-08-02', NULL, NULL);
INSERT INTO order_details VALUES
(381,1,1),(601,9,1),
(442,1,1),
(523,9,1),
(630,5,1),
(778,1,1),
(693,10,1),
(118,1,1),
(264,7,1),
(607,10,1),
(624,7,1),
(658,1,1),
(800,5,1),
(158,3,1),
(321,10,1),
(687,6,1),
(827,6,1),
(144,3,1),
(479,1,2),
(630,6,2),(796,5,1),(97,4,1),
(601,5,1),
(800,1,1),
(29,10,1),
(70,1,1),
(165,4,1),
(180,4,1),
(231,10,1),
(413,10,1),
(491,6,1),
(607,3,1),
(651,3,1),
(703,4,1),
(802,3,1),
(824,7,2),
(829,1,1),
(550,4,1),
(796,7,1),
(693,6,1),
(29,3,1),
(32,7,1),
(242,1,1),
(298,1,1),
(479,4,1),
(548,9,1),
(627,9,1),
(778,3,1),
(19,5,1),
(89,4,1),
(242,6,1),
(264,4,1),
(550,1,1),
(693,7,3),
(824,3,1),
(829,5,1),
(829,9,1);
Error Code: 1364. Field 'customer_address' doesn't have a default value 0.000 sec
That means that the customer_address column is set to NOT allow NULL values and that no default value has been specified. Therefore your insert statement must include the customer address field.
insert into customers (customer_first_name, customer_last_name, customer_address)
values ("Nathan", "Rivera", "1000 Fred St."),
("thom", "something", "9659 Foobar Dr.");
Now that you've added your table defs it's clear that you'll need the other fields that you've marked NOT NULL as well in the insert statement, or you'll see a similar error for each one you leave out.
You can specify a default value using the DEFAULT option in the CREATE TABLE query.
CREATE TABLE customers
(
customer_id INT,
customer_first_name VARCHAR(20),
customer_last_name VARCHAR(20) NOT NULL,
customer_address VARCHAR(50) NOT NULL DEFAULT '',
customer_city VARCHAR(20) NOT NULL DEFAULT '',
customer_state CHAR(2) NOT NULL DEFAULT '',
customer_zip CHAR(5) NOT NULL DEFAULT '',
customer_phone CHAR(10) NOT NULL DEFAULT '',
customer_fax CHAR(10),
CONSTRAINT customers_pk
PRIMARY KEY (customer_id)
);

mysql statement wont insert

Hey guys I've searched for answers through the forums but to no avail so I'm using MySql and I'm trying to insert statements for certain tables and they aren't going into the tables and I'm getting errors like "Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated. The statement has been terminated."
These are the statements I'm having problems with.`INSERT INTO Course VALUES
INSERT INTO Course VALUES (12345, 'DatabaseManagement', '2015-2-1', '2014-5-9');
INSERT INTO Course VALUES (12346, 'Calculus', '2015-1-12', '2015-5-9');
INSERT INTO Course VALUES (12347, 'Biology', '2015-1-3', '2015-5-9');
INSERT INTO Course VALUES (12348, 'Chemistry', '2015-1-2', '2015-5-9');
INSERT INTO Grade VALUES (10, 12345, 012, 'A');
INSERT INTO Grade VALUES (11, 12346, 013, 'B');
INSERT INTO Grade VALUES (12, 12347, 014, 'C');
INSERT INTO Grade VALUES (13, 12348, 015, 'D');
INSERT INTO Grade VALUES (14, 12345, 016, 'B');
INSERT INTO Student VALUES (54321, 'Rachel', 'Cotterel', '2013-4-15', '2016-3-4');
INSERT INTO Student VALUES (54320, 'John', 'Smith', '2012-1-23', NULL);
INSERT INTO Student VALUES (54319, 'Johny', 'Depp', '2010-5-12', '2012-10-10');
INSERT INTO Student VALUES (54318, 'Orlando', 'Bloom', '2014-6-24', NULL);
INSERT INTO Student VALUES (54317, 'Linda', 'Jacob', '2015-4-4', '2019-8-6');
I didn't get any error for insert into Course statements. I got error for INSERT INTO Grade statements. Its because there is no reference available for StudentID 012,013 etc in Student table. And you are trying to add them in grade table.
Try using this:
INSERT INTO table1 (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
These are the field types:
CREATE TABLE Course
(
CourseID int,
Description varchar(20) NOT NULL,
StartDate DATE NOT NULL,
EndDate DATE NOT NULL,
CONSTRAINT [PK_CourseID] PRIMARY KEY (CourseID)
);
CREATE TABLE Grade
(
GradeID integer(10) NOT NULL,
CourseID integer(10) NOT NULL,
StudentID integer(10) NOT NULL,
Grade varchar (10) NULL,
CONSTRAINT [PK_GradeID] PRIMARY KEY (GradeID),
CONSTRAINT [FK_CourseID] FOREIGN KEY (CourseID) REFERENCES Course(CourseID),
CONSTRAINT [FK_StudentID] FOREIGN KEY (StudentID) REFERENCES Student(StudentID)
);
CREATE TABLE Student
(
StudentID integer(10) NOT NULL,
FirstName varchar(45) NOT NULL,
LastName varchar(45) NOT NULL,
RegistrationDate varchar (45) NOT NULL,
GraduationDate DATE NULL,
CONSTRAINT [PK_StudentlID] PRIMARY KEY (StudentID)
);
String or binary data would be truncated
The reason that you get this message should be that you are trying to insert some value to some field to which you haven't assigned enough size to hold the value.
Can you send what the exact error message you get?
I tried to do it myself.But the error I got was from you insertion query to Grade table foreign key fails which refer Student table because you are trying to insert Student_IDs which are not there in you Student table

Aggregate Query depending on several tables

I want to create a database with information of employees, their jobs, salaries and projects
I want to keep information of the cost of a project (real value of project and the days a employee invested)
For employee and project each Employee has one role on the Project through the PK constraint, and allows for the addition of a new role type ("Tertiary" perhaps) in the future.
CREATE TABLE Employee(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Sex CHAR(1) NOT NULL,
Address VARCHAR(80) NOT NULL,
Security VARCHAR(15) NOT NULL,
DeptID INTEGER NOT NULL,
JobID INTEGER NOT NULL
);
CREATE TABLE Departments (
DeptID INTEGER NOT NULL PRIMARY KEY,
DeptName VARCHAR(30) NOT NULL
);
CREATE TABLE Jobs (
JobID INTEGER NOT NULL PRIMARY KEY,
JobName VARCHAR(30) NOT NULL,
JobSalary DOUBLE(15,3) NOT NULL default '0.000',
JobSalaryperDay DOUBLE(15,3) NOT NULL default '0.000',
DeptID INTEGER NOT NULL
);
CREATE TABLE Project(
ProjectID INTEGER NOT NULL PRIMARY KEY,
ProjectDesc VARCHAR(200) NOT NULL,
StartDate DATE NOT NULL,
EndDate DATE NOT NULL,
DaysOfWork INTEGER NOT NULL,
NoEmployees INTEGER NOT NULL,
EstimatedCost DOUBLE(15,3) NOT NULL default '0.000',
RealCost DOUBLE(15,3) NOT NULL default '0.000'
);
CREATE TABLE `Project-Employee`(
ProjectID INTEGER NOT NULL,
EmployeeID INTEGER NOT NULL,
Note VARCHAR(200),
DaysWork INTEGER NOT NULL,
CONSTRAINT fk_ProjectID FOREIGN KEY (ProjectID) REFERENCES Project(ProjectID),
CONSTRAINT fk_EmployeeID FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeID)
);
INSERT INTO `Departments` VALUES (1, 'Outsourcing');
INSERT INTO `Departments` VALUES (2, 'Technician');
INSERT INTO `Departments` VALUES (3, 'Administrative');
INSERT INTO `Jobs` VALUES (1, 'welder' ,500.550,16.7 ,2);
INSERT INTO `Jobs` VALUES (2, 'turner' ,500.100,16.67,2);
INSERT INTO `Jobs` VALUES (3, 'assistant' ,650.100,21.67,2);
INSERT INTO `Jobs` VALUES (4, 'supervisor',800.909,26.70,3);
INSERT INTO `Jobs` VALUES (5, 'manager' ,920.345,30.68,3);
INSERT INTO `Jobs` VALUES (6, 'counter' ,520.324,17.35,1);
INSERT INTO `Employee` VALUES (10, 'Joe', 'M', 'Anywhere', '927318344', 1, 3);
INSERT INTO `Employee` VALUES (20, 'Moe', 'M', 'Anywhere', '827318322', 2, 3);
INSERT INTO `Employee` VALUES (30, 'Jack', 'M', 'Anywhere', '927418343', 3, 4);
INSERT INTO `Employee` VALUES (40, 'Marge','F', 'Evererre', '127347645', 1, 6);
INSERT INTO `Employee` VALUES (50, 'Greg' ,'M', 'Portland', '134547633', 3, 5);
INSERT INTO `Project` VALUES (1, 'The very first', '2008-7-04' , '2008-7-24' , 20, 5, 3000.50, 2500.00);
INSERT INTO `Project` VALUES (2, 'Second one pro', '2008-8-01' , '2008-8-30' , 30, 5, 6000.40, 6100.40);
INSERT INTO `Project-Employee` VALUES (1, 10, 'Worked all days' , 20);
INSERT INTO `Project-Employee` VALUES (1, 20, 'Worked just in defs', 11);
INSERT INTO `Project-Employee` VALUES (1, 30, 'Worked just in defs', 17);
INSERT INTO `Project-Employee` VALUES (1, 40, 'Contability ' , 8);
INSERT INTO `Project-Employee` VALUES (1, 50, 'Managed the project', 8);
So to get the total amount of the cost of a project and have it for future Work quote I would just sum the working days of each job for each employee in an aggregate query.
What would be the query to sum all working days knowing the employees involved in a particular project to know the cost generated for their work, Is it possible to know this with this design?
So lets suppose I know that in project 1, 5 employees were involved, and I know by other table "jobs" the salary I would pay each one of them per day
I am doing some queries here with sqlfiddle
UPDATE
CREATE TABLE `Sexes` (
Sex char(1) primary key
);
INSERT INTO Sexes values ('M');
INSERT INTO Sexes values ('F');
CREATE TABLE `Employee`(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(130) NOT NULL,
Sex CHAR(1) NOT NULL,
Address VARCHAR(380) NOT NULL,
Security VARCHAR(15) NOT NULL,
FOREIGN KEY (Sex) references Sexes (Sex),
CONSTRAINT `uc_EmployeeInfo` UNIQUE (`EmployeeID`,`Name`,`Security`)
);
CREATE TABLE `Department` (
DeptID INTEGER NOT NULL PRIMARY KEY,
DeptName VARCHAR(30) NOT NULL,
CONSTRAINT `uc_DeptName` UNIQUE (`DeptID`,`DeptName`)
);
CREATE TABLE `Dept-Employee`(
EmployeeID INTEGER NOT NULL,
DeptID INTEGER NOT NULL,
CONSTRAINT fk_DeptID FOREIGN KEY (DeptID) REFERENCES `Department`(DeptID),
CONSTRAINT fk_EmployeeID FOREIGN KEY (EmployeeID) REFERENCES `Employee`(EmployeeID)
);
CREATE TABLE `Dept-Manager`(
EmployeeID INTEGER NOT NULL,
DeptID INTEGER NOT NULL,
CONSTRAINT fk_DeptIDs FOREIGN KEY (DeptID) REFERENCES `Department`(DeptID),
CONSTRAINT fk_EmployeeIDs FOREIGN KEY (EmployeeID) REFERENCES `Employee`(EmployeeID)
);
CREATE TABLE `Jobs` (
JobID INTEGER NOT NULL PRIMARY KEY,
JobName VARCHAR(30) NOT NULL,
JobSalary DECIMAL(7,3) NOT NULL default '0000.000',
JobSalaryperDay DECIMAL(7,3) NOT NULL default '0000.000',
CONSTRAINT `uc_jobs` UNIQUE (`JobID`,`JobName`)
);
CREATE TABLE `Jobs-Employee`(
EmployeeID INTEGER NOT NULL,
JobID INTEGER NOT NULL,
CONSTRAINT fk_JobIDs FOREIGN KEY (JobID) REFERENCES `Jobs`(JobID),
CONSTRAINT fk_EmployeeIDss FOREIGN KEY (EmployeeID) REFERENCES `Employee`(EmployeeID)
);
CREATE TABLE `Project`(
ProjectID INTEGER NOT NULL PRIMARY KEY,
ProjectName VARCHAR(200) NOT NULL,
StartDate DATE NOT NULL,
DaysOfWork INTEGER NOT NULL,
NoEmployees INTEGER NOT NULL,
EstimatedCost DECIMAL(9,3) NOT NULL default '000000.000',
RealCost DECIMAL(9,3) NOT NULL default '000000.000',
CONSTRAINT `uc_project` UNIQUE (`ProjectID`,`ProjectName`)
);
CREATE TABLE `Project-Employee`(
ProjectID INTEGER NOT NULL,
EmployeeID INTEGER NOT NULL,
Note VARCHAR(200),
DaysWork INTEGER NOT NULL,
CONSTRAINT fk_ProjectIDsss FOREIGN KEY (ProjectID) REFERENCES `Project`(ProjectID),
CONSTRAINT fk_EmployeeIDsss FOREIGN KEY (EmployeeID) REFERENCES `Employee`(EmployeeID)
);
INSERT INTO `Department` VALUES (1, 'Outsourcing');
INSERT INTO `Department` VALUES (2, 'Technician');
INSERT INTO `Department` VALUES (3, 'Administrative');
INSERT INTO `Jobs` VALUES (1, 'welder' ,500.550, 16.7 );
INSERT INTO `Jobs` VALUES (2, 'turner' ,500.100, 16.67);
INSERT INTO `Jobs` VALUES (3, 'assistant' ,650.100, 21.67);
INSERT INTO `Jobs` VALUES (4, 'supervisor',800.909, 26.70);
INSERT INTO `Jobs` VALUES (5, 'manager' ,920.345, 30.68);
INSERT INTO `Jobs` VALUES (6, 'counter' ,520.324, 17.35);
INSERT INTO `Employee` VALUES (10, 'Joe', 'M', 'Joewhere', '927318344');
INSERT INTO `Employee` VALUES (20, 'Moe', 'M', 'Moewhere', '827318322');
INSERT INTO `Employee` VALUES (30, 'Jack', 'M', 'Jaswhere', '927418343');
INSERT INTO `Employee` VALUES (40, 'Marge','F', 'Evererre', '127347645');
INSERT INTO `Employee` VALUES (50, 'Greg' ,'M', 'Portland', '134547633');
INSERT INTO `Dept-Employee` VALUES (10,1);
INSERT INTO `Dept-Employee` VALUES (20,2);
INSERT INTO `Dept-Employee` VALUES (30,3);
INSERT INTO `Dept-Employee` VALUES (40,1);
INSERT INTO `Dept-Employee` VALUES (50,3);
INSERT INTO `Jobs-Employee` VALUES (10,3);
INSERT INTO `Jobs-Employee` VALUES (20,3);
INSERT INTO `Jobs-Employee` VALUES (30,4);
INSERT INTO `Jobs-Employee` VALUES (40,6);
INSERT INTO `Jobs-Employee` VALUES (50,5);
INSERT INTO `Project` VALUES (1, 'The very first', '2008-7-04' , 20, 5, 3000.50, 2500.00);
INSERT INTO `Project` VALUES (2, 'Second one pro', '2008-8-01' , 30, 5, 6000.40, 6100.40);
INSERT INTO `Project-Employee` VALUES (1, 10, 'Worked all days' , 20);
INSERT INTO `Project-Employee` VALUES (1, 20, 'Worked just in defs', 11);
INSERT INTO `Project-Employee` VALUES (1, 30, 'Worked just in defs', 17);
INSERT INTO `Project-Employee` VALUES (1, 40, 'Contability ' , 8);
INSERT INTO `Project-Employee` VALUES (1, 50, 'Managed the project', 8);
To the new structure I did this
CREATE VIEW `Emp-Job` as
SELECT e.*,j.jobID
FROM Employee e,`Jobs-Employee` j
WHERE e.EmployeeID = j.EmployeeID;
CREATE VIEW `employee_pay` as
select e.*, j.jobname, j.jobsalary, j.jobsalaryperday
from `Emp-Job` e
inner join `Jobs` j
on e.JobID = j.JobID;
create view project_pay as
select pe.projectid, pe.employeeid, pe.dayswork,
e.jobsalaryperday, (e.jobsalaryperday * dayswork) as total_salary
from `Project-Employee` pe
inner join `employee_pay` e
on e.employeeid = pe.employeeid
The data at the end of your question doesn't seem to match the data in your INSERT statements.
Have you ever heard of "divide and conquer"? This is a good time to use it. Here's what I'd do.
create view employee_pay as
select e.*, j.jobname, j.jobsalary, j.jobsalaryperday
from employee e
inner join jobs j on e.jobid = j.jobid
create view project_pay as
select pe.projectid, pe.employeeid, pe.dayswork,
e.jobsalaryperday, (e.jobsalaryperday * dayswork) as total_salary
from project_employee pe
inner join employee_pay e
on e.employeeid = pe.employeeid
I'd do that, because I expect those views to be generally useful. (Especially for debugging.) Having created those views, the total for a project is dead simple.
select projectid, sum(total_salary) as total_salaries
from project_pay
group by projectid
projectid total_salaries
--
1 1509.91
You really don't want to use DOUBLE for money. Use DECIMAL instead.
Use this query to sort out why my sum doesn't match yours.
select p.*, e.name
from project_pay p
inner join employee e on e.employeeid = p.employeeid;
projectid employeeid dayswork jobsalaryperday total_salary name
1 10 20 21.67 433.4 Joe
1 20 11 21.67 238.37 Moe
1 30 17 26.7 453.9 Jack
1 40 8 17.35 138.8 Marge
1 50 8 30.68 245.44 Greg
Anti-patterns
Broken identity
Whenever you see a table like this one
CREATE TABLE Departments (
DeptID INTEGER NOT NULL PRIMARY KEY,
DeptName VARCHAR(30) NOT NULL
);
you should assume its structure is wrong, and dig deeper. (It's presumed guilty until proven innocent.) The anti-pattern you look for
integer as an artificial primary key, along with
no other unique constraints.
A table like this allows the real data to be duplicated, eliminating the usefulness of an artificial key.
DeptID DeptName
--
1 Wibble
2 Wibble
...
175 Wibble
A table like this will allow multiple foreign key references, too. That means some of the foreign keys might reference Wibble (DeptID = 1), some might reference Wibble (DeptID = 175), and so on.
To fix that, add a UNIQUE constraint on DeptName.
Missing foreign key references
Whenever you see a table like this one
CREATE TABLE Employee(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
...
DeptID INTEGER NOT NULL,
JobID INTEGER NOT NULL
);
you should assume its structure is wrong, and dig deeper. (Again, it's presumed guilty until proven innocent.) The anti-pattern you look for
ID numbers from other tables, along with
no foreign key constraints referencing those tables.
To fix that, add foreign key constraints for DeptID and JobID. On MySQL, make sure you're using the INNODB engine, too. (As of MySQL 5.6, MyISAM still won't enforce foreign key constraints, but it won't give you an error or warning if you write them. They're parsed and ignored.)
If you come to MySQL from another dbms, you'll be surprised to find that MySQL doesn't support inline foreign key reference syntax. That means you can't write this.
DeptID integer not null references Departments (DeptID)
Instead, you have to write a separate foreign key clause in the CREATE TABLE statement. (Or use a separate ALTER TABLE statement to declare the FK reference.)
DeptID integer not null,
foreign key (DeptID) references Departments (DeptID)
Search this page for "inline ref", but read the whole thing.
Missing CHECK() constraints
MySQL doesn't enforce CHECK() constraints, so for columns that beg for a CHECK() constraint, you need a table and a foreign key reference. When you see a structure like this
CREATE TABLE Employee(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Sex CHAR(1) NOT NULL,
the column "Sex" begs for a CHECK() constraint.
CREATE TABLE Employee(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Sex CHAR(1) NOT NULL CHECK( Sex IN ('M', 'F')),
But MySQL doesn't enforce CHECK() constraints, so you need another table and a foreign key reference.
create table sexes (
sex char(1) primary key
);
insert into sexes values ('M');
insert into sexes values ('F');
CREATE TABLE Employee(
EmployeeID INTEGER NOT NULL PRIMARY KEY,
Name VARCHAR(30) NOT NULL,
Sex CHAR(1) NOT NULL,
...
foreign key (Sex) references Sexes (Sex)
I'd consider CHECK() constraints for most of these columns. Some can be implemented as tables with foreign key references.
Employee.Security
Jobs.JobSalary
Jobs.JobSalaryperDay
Project.DaysOfWork
Project.NoEmployees
Project.EstimatedCost
Project.RealCost
Project_Employee.DaysWork
Using floating-point data types for money
Don't do that. Floating-point numbers are useful approximations, but they're still approximations. Use DECIMAL instead.