Unable to Add More Than One Field in Table in MySQL - mysql

I'm trying to add a table in a MySQL database. The database is called "stocks". The odd thing I'm encountering is that while I can create the table, I can't add any fields to it other than the primary key.
Code is below. Please note that I can create the "person" table and all of its fields and populate all fields without a problem. The "quotes" table and "person_quotes" table can be created, too, but I cannot populate them with any fields other than the primary key. Anyone have any idea what's going on?
/* delete tables if they exist already - ensuring a clean db */
DROP TABLE IF EXISTS stocks.person CASCADE;
DROP TABLE IF EXISTS stocks.quotes CASCADE;
DROP TABLE IF EXISTS stocks.person_quotes CASCADE;
/** creates a table to store a list of persons */
CREATE TABLE stocks.person
(
person_ID INT PRIMARY KEY NOT NULL,
first_name VARCHAR(256) NOT NULL,
last_name VARCHAR(256) NOT NULL,
birth_date DATETIME NOT NULL
);
/* creates a table to store a list of quotes */
CREATE TABLE stocks.quotes
(
quotes_ID INT PRIMARY KEY NOT NULL,
symbol VARCHAR(256) NOT NULL,
quote_time DATETIME NOT NULL,
price DECIMAL NOT NULL
);
/** A list of people and their quotes */
CREATE TABLE stocks.person_quotes
(
person_quote_ID INT PRIMARY KEY NOT NULL,
person_id INT NOT NULL,
quotes_id INT NOT NULL,
FOREIGN KEY (person_id) REFERENCES person (person_ID),
FOREIGN KEY (quotes_id) REFERENCES quotes (quotes_ID)
);
/** add some sample data */
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (1, 'GOOG', '2018-09-21 00:00:01', 85);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (2, 'GOOG', '2018-09-21 00:00:59', 95);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (3, 'GOOG', '2018-09-21 01:00:01', 105);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (4, 'GOOG', '2018-09-21 02:00:01', 115);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (5, 'GOOG', '2018-09-21 03:00:01', 125);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (6, 'GOOG', '2018-09-22 00:00:01', 135);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (7, 'GOOG', '2018-09-22 01:00:01', 145);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (8, 'GOOG', '2018-09-22 02:00:01', 155);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (9, 'GOOG', '2018-09-22 03:00:01', 165);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (10, 'GOOG', '2018-09-23 00:00:01', 175);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (11, 'GOOG', '2018-09-24 00:00:01', 185);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (12, 'GOOG', '2018-09-25 00:00:01', 195);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (13, 'GOOG', '2018-09-26 00:00:01', 205);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (14, 'GOOG', '2018-09-27 00:00:01', 215);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (15, 'GOOG', '2018-09-28 00:00:01', 225);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (16, 'GOOG', '2018-09-29 00:00:01', 235);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (17, 'GOOG', '2018-09-30 00:00:01', 245);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (18, 'GOOG', '2018-09-30 00:00:01', 255);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (19, 'GOOG', '2018-10-01 00:00:01', 265);
INSERT INTO quotes (quotes_ID,symbol,quote_time,price) VALUES (20, 'GOOG', '2018-10-02 00:00:01', 275);
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (1, 'Drew', 'Hope', '1999/10/10');
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (2, 'Lang', 'Heckman', '1959/11/11');
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (3, 'Lucy', 'Jones', '2010/1/1');
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (4, 'Stew', 'Hammer', '1990/3/28');
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (5, 'Dan', 'Lane', '1986/4/18');
INSERT INTO person (person_ID,first_name,last_name,birth_date) VALUES (6, 'James', 'Marrese', '1915/10/18');
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (1, 1, 2);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (2, 1, 1);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (3, 2, 1);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (4, 3, 1);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (5, 3, 3);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (6, 3, 4);
INSERT INTO person_quotes (person_quotes_ID, person_id, quotes_id) VALUES (7, 4, 7);

Related

Sum of multiple rows in sql with join statement

I am trying to sum multiple rows of the same athlete so it will return the total amount of medals that they have won overall. I have the following code:
CREATE TABLE athlete (
athlete_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
country TINYTEXT NOT NULL,
birthdate DATE NOT NULL,
age INT UNSIGNED,
height_inch INT UNSIGNED,
PRIMARY KEY (athlete_id)
);
INSERT INTO athlete (name, country, birthdate, age, height_inch) VALUES ('Simone Biles', 'United States', '1997-03-14', 24, 56);
INSERT INTO athlete (name, country, birthdate, age, height_inch) VALUES ('Michael Phelps', 'United States', '1985-06-30', 36, 76);
CREATE TABLE sport (
sport_id INT UNSIGNED NOT NULL,
sport TINYTEXT NOT NULL,
PRIMARY KEY (sport_id)
);
INSERT INTO sport VALUES (101, 'Skiing');
INSERT INTO sport VALUES (102, 'Biathlon');
INSERT INTO sport VALUES (103, 'Curling');
INSERT INTO sport VALUES (104, 'Skating');
INSERT INTO sport VALUES (105, 'Ice Hockey');
INSERT INTO sport VALUES (106, 'Luge');
INSERT INTO sport VALUES (107, 'Snowboard');
INSERT INTO sport VALUES (108, 'Basketball');
INSERT INTO sport VALUES (109, 'Gymnastics');
INSERT INTO sport VALUES (110, 'Swimming');
INSERT INTO sport VALUES (111, 'Diving');
INSERT INTO sport VALUES (112, 'Track and Field');
INSERT INTO sport VALUES (113, 'Badminton');
INSERT INTO sport VALUES (114, 'Tennis');
INSERT INTO sport VALUES (115, 'Volleyball');
INSERT INTO sport VALUES (116, 'Skateboard');
INSERT INTO sport VALUES (117, 'Soccer');
INSERT INTO sport VALUES (118, 'Golf');
INSERT INTO sport VALUES (119, 'Cycling');
INSERT INTO sport VALUES (120, 'Climbing');
INSERT INTO sport VALUES (121, 'Surfing');
INSERT INTO sport VALUES (122, 'Water Polo');
INSERT INTO sport VALUES (123, 'Karate');
CREATE TABLE olympics (
olympics_id INT UNSIGNED NOT NULL,
season TINYTEXT NOT NULL,
year YEAR NOT NULL,
city TINYTEXT NOT NULL,
PRIMARY KEY (olympics_id)
);
INSERT INTO olympics VALUES (1001, 'Summer', 1936, 'Berlin');
INSERT INTO olympics VALUES (1002, 'Summer', 1956, 'Melbourne');
INSERT INTO olympics VALUES (1003, 'Summer', 1960, 'Rome');
INSERT INTO olympics VALUES (1004, 'Summer', 1964, 'Tokyo');
INSERT INTO olympics VALUES (1005, 'Summer', 1976, 'Montreal');
INSERT INTO olympics VALUES (1006, 'Summer', 1984, 'Los Angelos');
INSERT INTO olympics VALUES (1007, 'Summer', 1996, 'Atlanta');
INSERT INTO olympics VALUES (1008, 'Summer', 2000, 'Sydney');
INSERT INTO olympics VALUES (1009, 'Summer', 2004, 'Athens');
INSERT INTO olympics VALUES (1010, 'Summer', 2008, 'Beijing');
INSERT INTO olympics VALUES (1011, 'Summer', 2012, 'London');
INSERT INTO olympics VALUES (1012, 'Summer', 2016, 'Rio de Janeiro');
INSERT INTO olympics VALUES (1013, 'Summer', 2020, 'Tokyo');
CREATE TABLE sport_events (
sport_id INT UNSIGNED NOT NULL,
event_id INT UNSIGNED NOT NULL,
event TINYTEXT NOT NULL,
PRIMARY KEY (event_id),
FOREIGN KEY (sport_id) REFERENCES sport (sport_id)
);
INSERT INTO sport_events VALUES (101, 501, 'Alpine Skiing');
INSERT INTO sport_events VALUES (101, 502, 'Cross-Country Skiing');
INSERT INTO sport_events VALUES (104, 503, 'Figure Skating');
INSERT INTO sport_events VALUES (101, 504, 'Freestyle Skiing');
INSERT INTO sport_events VALUES (104, 505, 'Short Track Speed Skating');
INSERT INTO sport_events VALUES (101, 506, 'Ski Jumping');
INSERT INTO sport_events VALUES (107, 507, 'Half-pipe');
INSERT INTO sport_events VALUES (101, 508, 'Half-pipe');
INSERT INTO sport_events VALUES (104, 509, 'Speed Skating');
INSERT INTO sport_events VALUES (109, 510, 'Artistic Gymnastics');
INSERT INTO sport_events VALUES (109, 511, 'Rhythmic Gymnastics');
INSERT INTO sport_events VALUES (115, 512, 'Beach Volleyball');
INSERT INTO sport_events VALUES (112, 513, 'High Jump');
INSERT INTO sport_events VALUES (112, 514, '100m');
INSERT INTO sport_events VALUES (112, 515, '200m');
INSERT INTO sport_events VALUES (112, 516, '400m');
INSERT INTO sport_events VALUES (112, 517, '800m');
INSERT INTO sport_events VALUES (112, 518, '4x100m relay');
INSERT INTO sport_events VALUES (112, 519, 'Triple Jump');
CREATE TABLE athlete_sport (
athlete_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
sport_id INT UNSIGNED NOT NULL,
PRIMARY KEY (athlete_id),
FOREIGN KEY (athlete_id) REFERENCES athlete (athlete_id),
FOREIGN KEY (sport_id) REFERENCES sport (sport_id)
);
INSERT INTO athlete_sport (sport_id) VALUES (109);
INSERT INTO athlete_sport (sport_id) VALUES (110);
CREATE TABLE compete (
athlete_id INT UNSIGNED NOT NULL,
olympics_id INT UNSIGNED NOT NULL,
sport_id INT UNSIGNED NOT NULL,
event_id INT UNSIGNED,
gold INT UNSIGNED,
silver INT UNSIGNED,
bronze INT UNSIGNED,
FOREIGN KEY (olympics_id) REFERENCES olympics (olympics_id),
FOREIGN KEY (athlete_id) REFERENCES athlete (athlete_id),
FOREIGN KEY (event_id) REFERENCES sport_events (event_id)
);
INSERT INTO compete VALUES (1, 1012, 109, 510, 4, 0, 1);
INSERT INTO compete VALUES (1, 1013, 109, 510, 0, 1, 1);
INSERT INTO compete VALUES (2, 1009, 110, NULL, 6, 0, 2);
INSERT INTO compete VALUES (2, 1010, 110, NULL, 8, 0, 0);
INSERT INTO compete VALUES (2, 1011, 110, NULL, 4, 2, 0);
INSERT INTO compete VALUES (2, 1012, 110, NULL, 5, 1, 0);
I have looked at other answers people have posted and most of them are just saying to use group by, but when I use that it just orders the either names or number of medals together just in a different order. I'm trying to get it so it says that the total number of medals simone biles has is 7 and michael phelps is 28 just in a single table.
This is the query I have that returns the sum of the medals for each olympic games they've been in, but again if I use group by it just orders them.
select a.name, gold+silver+bronze as medalTotal from athlete a join compete c using (athlete_id) group by medalTotal;
+----------------+------------+
| name | medalTotal |
+----------------+------------+
| Simone Biles | 2 |
| Simone Biles | 5 |
| Michael Phelps | 6 |
| Michael Phelps | 8 |
+----------------+------------+
you need to do the following:
group by athlete
sum each medal type
add the sum of each medal type
You need to group by athlete, not total.
You have to use an aggregation function to combine values from all the rows in a group. Use SUM() to add them together.
select a.name, SUM(b.gold+b.silver+b.bronze) as medalTotal
from athlete a
join compete c using (athlete_id)
group by a.athlete_id;
You should apply group by using something unique like athelet id.
This get all atheletes with all medals number including with zero medals
if you want just athelet with medals only use join only.
select
a.name, sum(gold+silver+bronze) as medalTotal
from
athlete a
left join
compete c on c.athlete_id = a.athlete_id
group by
a.athlete_id

Replacing int value with null

When I have an int column and most of the data is a number, but I have a few where there is no data and I am trying to fill it in with a null. how do you go about this? (In summary a null value in place of an int).
CREATE TABLE EmployeeSalary
(EmployeeID int,
JobTitle varchar(50),
YearsOfService int,
Salary int
);
INSERT INTO EmployeeSalary VALUES
(101, 'Manager', 20, 80000),
(102, 'Desk Clerk', 5, 30000),
(103, 'Maintanence', 10, 60000),
(104, 'Sales', 'null', 'null'),
(105, 'Operations Manager', 'null', 'null')
;
Remove quotes around null and put NULL in place of 'null'...
INSERT INTO EmployeeSalary (emp_id, emp_post, how_much_year, emp_salary) VALUES
(1, 'Computer Engineer', 20, NULL),
(2, 'Computer Scientist', NULL, 100000);
The value 'NULL', with single quotes around it, is a string literal. You want to use NULL, without quotes:
INSERT INTO EmployeeSalary (EmployeeID, JobTitle, YearsOfService, Salary)
VALUES
(101, 'Manager', 20, 80000),
(102, 'Desk Clerk', 5, 30000),
(103, 'Maintanence', 10, 60000),
(104, 'Sales', NULL, NULL),
(105, 'Operations Manager', NULL, NULL);
Note that I also added the target colums of the insert, which is considered best practice.
You are trying to save text value in YearOfService column. Whenever you wrap any value in-between apostrophe i.e. ' then it becomes a text value .
Use null instead of 'null' it should work.
Valid insert query:
INSERT INTO EmployeeSalary VALUES
(101, 'Manager', 20, 80000),
(102, 'Desk Clerk', 5, 30000),
(103, 'Maintanence', 10, 60000),
(104, 'Sales', null, null),
(105, 'Operations Manager', null, null)
;
Please refer this db-fiddle

When I try to create a table in MySQL, it gives me error code 1215: “Cannot add foreign key constraint”

I am trying to create a database, but when I run this code, I get this error:
Code 1215: “Cannot add foreign key constraint"
Code:
drop database if exists kat_db;
create database if not exists kat_db;
use kat_db;
create table if not exists Patients
(
PatientID int not null PRIMARY KEY,
PatientName varchar(50),
TypeOfAnimal varchar(50),
DateOfLastApt date,
PatientAge int,
Microchipped boolean,
OwnerID int not null,
DoctorID int not null,
foreign key (OwnerID) references Owners(OwnerID),
foreign key (DoctorID) references Doctors(DoctorID)
);
create table if not exists Owners
(
OwnerID int not null PRIMARY KEY,
OwnerFirstName varchar(50),
OwnerLastName varchar(50),
PatientID int,
OwnerPhone int,
OwnerZip int,
PreferredPaymentMethod varchar(50),
foreign key (PatientID) references Patients(PatientID)
);
create table if not exists Doctors
(
DoctorID int not null PRIMARY KEY,
DoctorFirstName varchar(50),
DoctorLastName varchar(50),
PatientID int,
DoctorPhone int,
DoctorZip int,
AnimalSpecialty varchar(50),
foreign key (PatientID) references Patients(PatientID)
);
insert into Patients (PatientID, TypeOfAnimal, PatientAge, PatientName, DateOfLastApt, Microchipped, DoctorID, OwnerID)
values (01, 'dog', 6, 'Dima', '2017-02-05', 1, 101, 1001),
(02, 'dog', 3, 'Misha', '2017-02-05', 1, 102, 1002),
(03, 'cat', 2, 'Pistol', '2017-06-09', 0, 103, 1003),
(04, 'cat', 1, 'Nessie', '2017-09-04', 0, 104, 1004),
(05, 'cat', 2, 'Charlie', '2016-06-04', 1, 105, 1005),
(06, 'cat', 12, 'Francis', '2015-05-07', 1, 106, 1006),
(07, 'rabbit', 5, 'Bunny', '2015-05-06', 0, 107, 1007),
(08, 'turtle', 6, 'Aqua', '2017-06-08', 0, 108, 1008),
(09, 'dog', 16, 'Sammie', '2012-09-07', 1, 109, 1009),
(10, 'dog', 14, 'Dog', '2016-04-06', 0, 110, 1010);
insert into Owners (OwnerID, OwnerFirstName, OwnerLastName, OwnerPhone, OwnerZip, PreferredPaymentMethod, PatientID)
values (101, 'Kat', 6, 'Dima', '2017-02-05', 1, 101, 1001),
(102, 'Hunter', 3, 'Misha', '2017-02-05', 1, 102, 1002),
(103, 'Vicky', 2, 'Pistol', '2017-06-09', 0, 103, 1003),
(104, 'Vanessa', 1, 'Nessie', '2017-09-04', 0, 104, 1004),
(105, 'Weston', 2, 'Charlie', '2016-06-04', 1, 105, 1005),
(106, 'Jonas', 12, 'Francis', '2015-05-07', 1, 106, 1006),
(107, 'Devin', 5, 'Bunny', '2015-05-06', 0, 107, 1007),
(108, 'Grego', 6, 'Aqua', '2017-06-08', 0, 108, 1008),
(109, 'Jackson', 16, 'Sammie', '2012-09-07', 1, 109, 1009),
(110, 'dog', 14, 'Dog', '2016-04-06', 0, 110, 1010);
insert into Patients (PatientID, TypeOfAnimal, PatientAge, PatientName, DateOfLastApt, Microchipped, DoctorID, OwnerID)
values (01, 'dog', 6, 'Dima', '2017-02-05', 1, 101, 1001),
(02, 'dog', 3, 'Misha', '2017-02-05', 1, 102, 1002),
(03, 'cat', 2, 'Pistol', '2017-06-09', 0, 103, 1003),
(04, 'cat', 1, 'Nessie', '2017-09-04', 0, 104, 1004),
(05, 'cat', 2, 'Charlie', '2016-06-04', 1, 105, 1005),
(06, 'cat', 12, 'Francis', '2015-05-07', 1, 106, 1006),
(07, 'rabbit', 5, 'Bunny', '2015-05-06', 0, 107, 1007),
(08, 'turtle', 6, 'Aqua', '2017-06-08', 0, 108, 1008),
(09, 'dog', 16, 'Sammie', '2012-09-07', 1, 109, 1009),
(10, 'dog', 14, 'Dog', '2016-04-06', 0, 110, 1010);
I tried creating the tables in different order. I also created a different database, which worked, In fact, I used this to create the database on the top.
drop database if exists kat3_db;
create database if not exists kat3_db;
use kat3_db;
create table if not exists Book(
BookNumber int not null,
BookName varchar(50),
BookPrice decimal(5,2),
CoverType varchar(15) default 'hardcover',
PublicationDate date,
primary key (BookNumber)
);
create table if not exists Course(
CourseNo int not null,
CourseName varchar(20),
Semester varchar(10),
BookNumber int not null,
primary key (CourseNo),
foreign key (BookNumber) references Book(BookNumber)
);
insert into Book
(BookNumber, BookName, BookPrice, CoverType, PublicationDate)
values
(1, 'Math', 023.64, 'paperback', '1999-02-05'),
(3, 'English', 999.36, 'e-book', '2013-06-04'),
(5, 'Calc', 056.69, 'paperback', '1964-05-05'),
(6, 'C++', 053.98, 'paperback', '2016-03-04'),
(7, 'Programming', 113.02, 'paperback', '2001-10-11'),
(9, 'Art', 250.99, 'paperback', '1996-11-11'),
(10, 'Networking', 036.64, 'e-book', '2014-05-06'),
(12, 'Drawing', 111.36, 'paperback', '2013-06-04'),
(13, 'Robotics', 012.03, 'e-book', '2016-06-05'),
(14, 'Computer', 25.03, 'e-book', '2001-06-04')
;
insert into Book
(BookNumber, BookName, BookPrice, PublicationDate)
values
(2, 'Reading', 364.20, '2016-06-05'),
(4, 'Database', 036.64, '2017-06-05'),
(8, 'Wellness', 050.00, '1999-10-10'),
(11, 'Linux', 55.36, '2013-06-08'),
(15, 'FYE', 03.01, '1991-02-05')
;
insert into Course
(CourseNo, CourseName, Semester, BookNumber)
values
(111, 'IntroToMath', 'Spring', 1),
(222, 'IntroToReading', 'Fall', 2),
(333, 'IntroToEnglish', 'Spring', 3),
(444, 'IntroToDatabase', 'Fall', 4),
(555, 'IntroToCalc', 'Spring', 5),
(666, 'IntroToC++', 'Spring', 6),
(777, 'IntroToProgramming', 'Fall', 7),
(888, 'IntroToWellness','Spring', 8),
(999, 'IntroToArt', 'Fall', 9),
(010, 'IntroToNetworking', 'Spring', 10),
(011, 'IntroToLinux', 'Fall', 11),
(012, 'IntroToDrawing', 'Spring', 12),
(013, 'IntroToRobotics', 'Fall', 13),
(014, 'IntroToComputer', 'Spring', 14),
(015, 'IntroToFYE', 'Summer', 15)
;
I do not see what I did differently. Any suggestions would be greatly appreciated. If someone can run the first code on top and tell me if it works for them or not, that would be big help also. Thank you!
At the time of creating Patients table, owner and Doctor table information is not available. So it is not allowing you.
So just create the table first.
and then add FK with alter table.
You're adding you tables in the wrong order.
You create the Patients table with foreign key constraints before you create the tables/fields they rely on to exist.

Integrity constraint (LEETO14.SYS_C00414504) violated

I can't figure out why I'm getting this error:
integrity constraint (LEETO14.SYS_C00414504) violated - parent key
not found
Everything works up until the insert values for CurrentLoan. Here is my code:
CREATE TABLE Book
(bookID INT PRIMARY KEY,
ISBN INT,
title varchar (20),
author varchar (20),
publish_year INT,
category varchar(20));
CREATE TABLE Member
(memberID INT PRIMARY KEY,
lastname varchar (20),
firstname varchar (20),
address varchar(20),
phone_number INT,
limit_ INT);
CREATE TABLE CurrentLoan
(memberID INT,
bookID INT,
loan_date DATE,
due_date DATE,
PRIMARY KEY (memberID, bookID),
FOREIGN KEY (memberID) REFERENCES Member(memberID),
FOREIGN KEY (bookID) REFERENCES Book(bookID));
INSERT INTO Book VALUES (10, 1113312336, 'The Dog', 'Jack Crow', 1990, 'fiction');
INSERT INTO Book VALUES (12, 2221254896, 'Worms', 'Jim Kan', 2013, 'fiction');
INSERT INTO Book VALUES (13, 3332546987, 'Crow', 'Jan Flo', 2000, 'fiction');
INSERT INTO Book VALUES (14, 4443456215, 'Big Dog', 'Lan Big', 1993, 'fiction');
INSERT INTO Book VALUES (15, 5552314569, 'Green Apple', 'Theo Brown', 1978, 'fiction');
INSERT INTO Book VALUES (16, 6664581631, 'Red Bean', 'Khang Nk', 2017, 'fiction');
INSERT INTO Book VALUES (17, 7771452369, 'The Dark Car', 'Author Le', 2017, 'fiction');
INSERT INTO Book VALUES (18, 8881245525, 'The Dark Room', 'Jack Se', 2017, 'fiction');
INSERT INTO Book VALUES (19, 9991123546, 'Lonely Mens', 'Geen Brown', 2014, 'fiction');
INSERT INTO Book VALUES (20, 1122112356, 'The Big Tree', 'Heart Le', 2002, 'fiction');
INSERT INTO Member VALUES (001, 'Lee', 'Nancy', 'Brownlea Drive', 1254896325, 2);
INSERT INTO Member VALUES (002, 'Le', 'Ray', '10th Street', 1234561256, 2);
INSERT INTO Member VALUES (003, 'Kan', 'Charlie', '5th Street', 1234567236, 2);
INSERT INTO Member VALUES (004, 'Brown', 'Joe', 'Elm Street', 1234567845, 2);
INSERT INTO Member VALUES (005, 'Smith', 'John', '33 East', 1234567890, 2);
INSERT INTO CurrentLoan VALUES (00123, 0236, '13-SEP-17', '14-NOV-17');
INSERT INTO CurrentLoan VALUES (00134, 2350, '13-JAN-17', '15-NOV-17');
INSERT INTO CurrentLoan VALUES (00125, 2034, '14-FEB-17', '12-MAR-17');
INSERT INTO CurrentLoan VALUES (00345, 0105, '12-OCT-17', '09-NOV-17');
INSERT INTO CurrentLoan VALUES (00311, 5012, '13-APR-17', '12-MAY-17');
INSERT INTO CurrentLoan VALUES (00213, 2051, '11-JUN-17', '02-OCT-17');
The answer is pretty self explanatory. You have foreign keys in the table, CurrentLoan. Looking at your insert statement, you're trying to add loans for members that you have not created and books you have not created.

MySQL Query Optimization - Avoiding Subqueries

I need to update some rows in my table, for simplicity called "three".
I select the columns to update with this query:
SELECT one.id
FROM one
JOIN `two` ON ( one.id = two.page )
JOIN `three` ON ( one.id = three.item )
WHERE two.level = 1
AND two.item = (SELECT item FROM two WHERE page = 5 AND level = 1 )
AND three.position > (SELECT position FROM three WHERE item = 5 )
ORDER BY three.position
Now I call an update query with id's I get.
Is there any chance to eliminate the subqueries?
Edit (after Melanie's comment):
Table "one":
|id|text|
Table "two":
|id|item|page|level|
Table "three":
|item|position|
So when I run the query
SELECT item FROM two WHERE page = 5 AND level = 1
It will return f.ex 1 and the final WHERE clause will be:
two.item = 1 AND two.level = 1
Which is not the same as:
two.level = 1 and two.page = 5
I have the table one - some text with some one.id. I need to update all items from table three which has higher position than my item (f.ex. id = 5) have. But those items should also have the same two.item in table two, where two.page = one.id and level = 1
I am sorry for a poor description.
You should be able to replace those subqueries by joins:
SELECT one.id
FROM one
JOIN `two2` ON (two2.page = 5 AND two2.level = 1)
JOIN `two` ON ( one.id = two.page AND two.item = two2.item )
JOIN `three2` ON ( three.item = 5)
JOIN `three` ON ( one.id = three.item AND three.position > three2.position)
WHERE two.level = 1
ORDER BY three.position
#TheVedge is interesting solution but does not produce the same result as your query
I suggest to avoid duplicate the same table also with a view so a little correction
Another correction is three2.item=5
I suggest to use in subquery limit 0,1 so never return more then one element
SELECT one.id
FROM one
JOIN `two` AS TWO2 ON (two2.page = 5 AND two2.level = 1)
JOIN `two` ON ( one.id = two.page AND two.item = two2.item )
JOIN `three` AS THREE2 ON ( three2.item = 5)
JOIN `three` ON ( one.id = three.item AND three.position > three2.position)
WHERE two.level = 1
ORDER BY three.position
Remember that you are not doing the same thing with this query.
Try this
CREATE TABLE `one` (
`id` INT(10) NULL DEFAULT NULL,
`text` VARCHAR(50) NULL DEFAULT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
_
CREATE TABLE `three` (
`item` INT(10) NULL DEFAULT NULL,
`position` INT(10) NULL DEFAULT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
_
CREATE TABLE `two` (
`id` INT(10) NULL DEFAULT NULL,
`item` INT(10) NULL DEFAULT NULL,
`page` INT(10) NULL DEFAULT NULL,
`level` INT(10) NULL DEFAULT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
_
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (1, 1, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (3, 3, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (4, 4, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (5, 5, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (6, 6, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (7, 7, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (8, 8, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (9, 9, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (2, 2, 5, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (10, 2, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (11, 1, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (13, 3, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (14, 4, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (15, 5, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (16, 6, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (17, 7, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (18, 8, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (19, 9, 1, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (20, 2, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (21, 1, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (23, 3, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (24, 4, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (25, 5, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (26, 6, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (27, 7, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (28, 8, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (29, 9, 2, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (30, 2, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (31, 1, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (33, 3, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (34, 4, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (35, 5, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (36, 6, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (37, 7, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (38, 8, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (39, 9, 3, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (40, 2, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (41, 1, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (42, 3, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (43, 4, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (44, 5, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (45, 6, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (46, 7, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (47, 8, 4, 1);
INSERT INTO `two` (`id`, `item`, `page`, `level`) VALUES (48, 9, 4, 1);
-
INSERT INTO `three` (`item`, `position`) VALUES (1, 1);
INSERT INTO `three` (`item`, `position`) VALUES (2, 1);
INSERT INTO `three` (`item`, `position`) VALUES (3, 1);
INSERT INTO `three` (`item`, `position`) VALUES (4, 1);
INSERT INTO `three` (`item`, `position`) VALUES (5, 0);
INSERT INTO `three` (`item`, `position`) VALUES (6, 1);
INSERT INTO `three` (`item`, `position`) VALUES (7, 1);
INSERT INTO `three` (`item`, `position`) VALUES (8, 1);
INSERT INTO `three` (`item`, `position`) VALUES (9, 1);
INSERT INTO `three` (`item`, `position`) VALUES (10, 1);
INSERT INTO `three` (`item`, `position`) VALUES (11, 1);
INSERT INTO `three` (`item`, `position`) VALUES (12, 1);
_
INSERT INTO `one` (`id`, `text`) VALUES (1, 'A');
INSERT INTO `one` (`id`, `text`) VALUES (2, 'B');
INSERT INTO `one` (`id`, `text`) VALUES (3, 'C');
INSERT INTO `one` (`id`, `text`) VALUES (4, 'D');
INSERT INTO `one` (`id`, `text`) VALUES (5, 'E');
INSERT INTO `one` (`id`, `text`) VALUES (6, 'F');
INSERT INTO `one` (`id`, `text`) VALUES (7, 'G');
_
SELECT
one.id, one.text
,two.id,two.item,two.page,two.level
,three.item,three.position
FROM one
JOIN `two` ON ( one.id = two.page )
JOIN `three` ON ( one.id = three.item )
WHERE two.level = 1
AND two.item = (SELECT item FROM two WHERE page = 5 AND level = 1 limit 0,1 )
AND three.position > (SELECT position FROM three WHERE item = 5 limit 0,1 )
ORDER BY three.position
SELECT
one.id, one.text
,two.id,two.item,two.page,two.level
,three.item,three.position
FROM one
JOIN `two` AS TWO2 ON (two2.page = 5 AND two2.level = 1)
JOIN `two` ON ( one.id = two.page AND two.item = two2.item )
JOIN `three` AS THREE2 ON ( three2.item = 5)
JOIN `three` ON ( one.id = three.item AND three.position > three2.position)
WHERE two.level = 1
ORDER BY three.position
With original query you made a select of specific element in TheVedge solution you are joining more data
So result depend on what you select
Another useful analysis is http://dev.mysql.com/doc/refman/5.0/en/show-profile.html and Explain
Show Profile show that at the first run
your original query does
Status Duration
starting 0.000039
checking query cache for query 0.000144
Opening tables 0.000032
System lock 0.000007
Table lock 0.000061
init 0.000054
optimizing 0.000314
statistics 0.000021
preparing 0.000051
Creating tmp table 0.000084
executing 0.000004
Copying to tmp table 0.000063
optimizing 0.000008
statistics 0.000019
preparing 0.000009
executing 0.000004
Sending data 0.000054
optimizing 0.000008
statistics 0.000007
preparing 0.000009
executing 0.000003
Sending data 0.000126
Sorting result 0.000030
Sending data 0.000025
end 0.000004
removing tmp table 0.000011
end 0.000005
query end 0.000004
freeing items 0.000101
storing result in query cache 0.000008
logging slow query 0.000003
cleaning up 0.000006
Proposed query does
Status Duration
starting 0.000036
checking query cache for query 0.000122
Opening tables 0.000030
System lock 0.000008
Table lock 0.000064
init 0.000046
optimizing 0.000028
statistics 0.000026
preparing 0.000072
Creating tmp table 0.000086
executing 0.000005
Copying to tmp table 0.001081
Sorting result 0.000040
Sending data 0.000056
end 0.000005
removing tmp table 0.000010
end 0.000005
query end 0.000004
freeing items 0.000108
storing result in query cache 0.000007
logging slow query 0.000003
cleaning up 0.000005
So when you have full data you can try to evalute better the response of both query