I need to insert some data into the 'ItemBook' table after inserting the following values for one row for the 'Item' Table:
Name='Clippers', itemLink='amazon.com' description='hair clippers'
Now I would also like to insert some data to the ItemBook table as well but I am not sure on how to do this with a table that has a foreign key. Here is the SQL code:
CREATE TABLE Item (
Name VARCHAR(100) NOT NULL,
itemLink VARCHAR(100) NOT NULL,
description VARCHAR(1000) NOT NULL,
PRIMARY KEY (Name)
);
CREATE TABLE ItemBook (
ItemName VARCHAR(100) NOT NULL,
Publisher VARCHAR(100) NOT NULL,
PRIMARY KEY (ItemName),
FOREIGN KEY (ItemName) REFERENCES Item(Name)
);
My attempt:
INSERT INTO itemBook (Name, Publisher)
VALUES ('Clippers', 'Bob');
Error Msg:
Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column. To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
Other Attempt:
INSERT INTO eventbook (EventName, Publisher)
SELECT E.name
FROM event E
WHERE E.name = eventbook.EventName;
Error Message:
Error Code: 1054. Unknown column 'eventbook.EventName' in 'where clause'
Is there any specific reason to not use integer IDs? I would do the following:
CREATE TABLE Item (
Id INTEGER NOT NULL IDENTITY PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
itemLink VARCHAR(100) NOT NULL,
description VARCHAR(1000) NOT NULL,
);
CREATE TABLE ItemBook (
Id INTEGER NOT NULL IDENTITY PRIMARY KEY,
ItemName VARCHAR(100) NOT NULL,
Publisher VARCHAR(100) NOT NULL,
ItemId INTEGER NOT NULL,
FOREIGN KEY (ItemId) REFERENCES Item(Id)
);
INSERT INTO ItemBook Values(1, 'ItemName', 'Publisher', 0)
What are your thoughts?
Edit 1. Based on your response and example, I have produced the following SQL for SQLITE (should work fine in other DBs as well)
CREATE TABLE Item (
Name VARCHAR(100) NOT NULL,
ItemLink VARCHAR(100) NOT NULL,
Description VARCHAR(1000) NOT NULL,
PRIMARY KEY (Name)
);
CREATE TABLE ItemBook (
ItemName VARCHAR(100) NOT NULL,
Publisher VARCHAR(100) NOT NULL,
PRIMARY KEY (ItemName),
FOREIGN KEY (ItemName) REFERENCES Item(Name)
);
INSERT INTO Item (Name, ItemLink, Description) VALUES("Test Book", "http://www.testlink.com/", "This is a test book");
INSERT INTO ItemBook (ItemName, Publisher) Values("Test Book", "Test Publisher");
SELECT * FROM Item i JOIN ItemBook b on b.ItemName = i.Name
Check the result in this print
Need some help please. Creating a basic relational database and trying to add column values from my account table to my login table. However, bit stuck on how to achieve this. I'm trying to take the AccountID, Username, Sign_in data to populate the Login table but nothing appear when executed.
my code:
CREATE TABLE IF NOT EXISTS Account
(
AccountID int NOT NULL AUTO_INCREMENT,
Title VARCHAR(64) NOT NULL,
FirstName varchar(16) NOT NULL,
LastName varchar(32) NOT NULL,
DOB DATE,
Email VARCHAR(255),
Username varchar(32) UNIQUE NOT NULL,
Sign_in varchar(32) UNIQUE NOT NULL,
PRIMARY KEY (AccountID)
);
ALTER TABLE Account AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS Login
(
LoginID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
AccountID INT NOT NULL,
Username varchar(32) NOT NULL,
Sign_in varchar(32) NOT NULL,
LoginDate TIMESTAMP(6),
FOREIGN KEY (AccountID) REFERENCES Account(AccountID),
FOREIGN KEY (Username) REFERENCES Account(Username),
FOREIGN KEY (Sign_in) REFERENCES Account(Sign_in)
);
ALTER TABLE Login AUTO_INCREMENT=100;
and tried the query (edited from a similar query found on this forum) to no avail
INSERT INTO Login
(
AccountID,
Username,
Sign_in
)
SELECT
a.AccountID, a.Username, a.Sign_in
FROM Account a
INNER JOIN Login
ON a.AccountID = l.AccountID;
Select * from Login;
Help/advice appreciated.
You are missing the point of relational databases. You simply want to map to the primary key and then look up the other values. You don't want to store the values in two places.
So:
CREATE TABLE IF NOT EXISTS Account (
AccountID int AUTO_INCREMENT PRIMARY KEY,
Title VARCHAR(64) NOT NULL,
FirstName varchar(16) NOT NULL,
LastName varchar(32) NOT NULL,
DOB DATE,
Email VARCHAR(255),
Username varchar(32) UNIQUE NOT NULL,
Sign_in varchar(32) UNIQUE NOT NULL
);
CREATE TABLE IF NOT EXISTS Login (
LoginID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
AccountID INT NOT NULL,
LoginDate TIMESTAMP(6),
FOREIGN KEY (AccountID) REFERENCES Account(AccountID)
);
Then if you want the username or sign_in, you use a JOIN to look up that information.
I don't see a reason to set the auto-increment values. There is generally no problem having them start at 1 in all tables.
Managed to work it out...
INSERT INTO Login (AccountID, Username, Sign_in)
SELECT AccountID, Username, Sign_in
FROM Account;
Did take on board the advice regarding the Primary Key ID suggestion though. Cheers
I want 'ProjectID' to start at 1000 and increment by 100.
How do I set an AUTO_INCREMENT default value and rate in MySQL 5.6? In other words, if I want to create a primary key that starts at 1000 and increases by 100, how do I do that in MySQL?
CREATE TABLE IF NOT EXISTS PROJECT(
ProjectID Int(4) AUTO_INCREMENT PRIMARY KEY,
ProjectName Char(20) NOT NULL,
DepartmentName Char(30) NOT NULL,
MaxHours Int(14) NOT NULL,
StartDate Char(10) NOT NULL,
EndDate Char(10) NULL)
ENGINE=InnoDB AUTO_INCREMENT=1000;
I want 'ProjectID' to start at 1000 and increment by 100.
Start with empty table.
ALTER TABLE tblName AUTO_INCREMENT = 1000;
Perform your insert to this special 100 gap table in one and only one place.
Let's call that place a stored proc (not mandatory).
Commit to the discipline of that approach.
In that stored proc lock the table, do an insert.
DECLARE a query as a "string" and then execute that string via a Prepared Statement. That string is like the above Alter Table but with auto_increment=xxxx
Where xxxx=max(ProjectID)+100
Unlock table. Exit stored proc.
The reason is that Alter Table tblName auto_increment = variable_name will barf. So it needs to be an executed Prepared Statement.
Edit as promised:
drop schema wpc;
CREATE SCHEMA IF NOT EXISTS WPC;
use wpc;
CREATE TABLE IF NOT EXISTS department
(
Department varchar(30) NOT NULL, -- chg
BudgetCode int(20) NOT NULL,
OfficeNumber int(10) NOT NULL,
Phone varchar(12) DEFAULT NULL, -- chg
PRIMARY KEY (Department)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS employee
(
EmployeeNumber int(4) AUTO_INCREMENT,
FirstName varchar(25) NOT NULL, -- chg
LastName varchar(25) NOT NULL, -- chg
Department varchar(30) NOT NULL DEFAULT 'Human Resources',
Phone varchar(17) DEFAULT NULL, -- chg
Email varchar(100) NOT NULL,
PRIMARY KEY (EmployeeNumber),
UNIQUE KEY Email (Email),
KEY DepartmentFK (Department),
CONSTRAINT DepartmentFK
FOREIGN KEY (Department)
REFERENCES department (Department) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS project
(
ProjectID INT(4) NOT NULL AUTO_INCREMENT,
ProjectName VARCHAR(30) NOT NULL, -- chg
Department VARCHAR(30) NOT NULL, -- chg
MaxHours INT(3) NOT NULL DEFAULT '100',
StartDate datetime NOT NULL, -- chg
EndDate datetime DEFAULT NULL, -- chg
PRIMARY KEY (ProjectID),
KEY ProjectFK (Department),
CONSTRAINT ProjectFK
FOREIGN KEY (Department)
REFERENCES department (Department) ON UPDATE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=LATIN1 AUTO_INCREMENT=1000;
CREATE TABLE IF NOT EXISTS assignment
(
ProjectID INT(4) NOT NULL AUTO_INCREMENT,
EmployeeNumber INT(4) NOT NULL,
HoursWorked INT(4) NOT NULL,
PRIMARY KEY (ProjectID),
-- UNIQUE KEY EmployeeNumber (EmployeeNumber), -- kill this dupe, plus it won't be unique
-- KEY ProjectFK1 (ProjectID), -- don't have this it is already a PK
KEY EmployeeFK1 (EmployeeNumber), -- keep this as it won't be unique
-- duplicate and unnecessary keys just slow down system. you had 4. you need 2
CONSTRAINT EmployeeFK1
FOREIGN KEY (EmployeeNumber)
REFERENCES employee (EmployeeNumber),
CONSTRAINT ProjectFK1
FOREIGN KEY (ProjectID)
REFERENCES project (ProjectID) ON DELETE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=LATIN1;
show table status like '%'; -- auto_incs look good
insert project (ProjectName,Department,MaxHours,StartDate,EndDate) values ('Dismantle Kryptonite','Engineering',1000,'2015-04-01',null);
-- fk error, good, do dept first. BUT NOTE this failure screws up auto_inc so next insert is 1001 yikes
-- so re-do, drop schema, create schema, skip failed first insert above and start below:
insert department (Department,BudgetCode,OfficeNumber,Phone) values ('Engineering',111,222,null);
insert department (Department,BudgetCode,OfficeNumber,Phone) values ('Human Resources',107,223,null);
select * from department;
-- all looks well
insert project (ProjectName,Department,MaxHours,StartDate,EndDate) values ('Dismantle Kryptonite','Engineering',1000,'2015-04-01',null);
select * from project; -- projectId 1000
alter table project auto_increment=1010;
insert project (ProjectName,Department,MaxHours,StartDate,EndDate) values ('Fire old employees','Human Resources',2,'2015-04-02',null);
alter table project auto_increment=1020;
insert project (ProjectName,Department,MaxHours,StartDate,EndDate) values ('Regret, Hire back','Human Resources',2,'2015-04-02',null);
alter table project auto_increment=1030;
select * from project;
fk's look good and as expected. Try employee:
insert employee (EmployeeNumber,FirstName,LastName,Department,Phone,Email) values (222,'Donald','','bad-dept','1','d#g.com');
insert employee (EmployeeNumber,FirstName,LastName,Department,Phone,Email) values (222,'Donald','','Engineering','1','d#g.com');
insert employee (EmployeeNumber,FirstName,LastName,Phone,Email) values (223,'Kris','','2','k#g.com');
insert employee (EmployeeNumber,FirstName,LastName,Phone,Email) values (2277,'Kim','','3','kim#g.com');
select * from employee;
insert employee (FirstName,LastName,Phone,Email) values ('Auto','','44','auto1#g.com'); -- 2278
do a re-do of everything top to bottom but skipping employee inserts except the below to run:
insert employee (FirstName,LastName,Department,Phone,Email) values ('Donald','','Engineering','1','d#g.com');
insert employee (FirstName,LastName,Phone,Email) values ('Kris','','2','k#g.com');
insert employee (FirstName,LastName,Phone,Email) values ('Kim','','3','kim#g.com');
select * from employee;
insert project (ProjectName,Department,MaxHours,StartDate,EndDate) values ('Hire Joe','Human Resources',2,'2015-05-02',null);
alter table project auto_increment=1040;
insert employee (FirstName,LastName,Phone,Email) values ('Jason','','66','jj#g.com');
select * from employee;
select * from project;
Create table:
CREATE TABLE IF NOT EXISTS PROJECT(
ProjectID Int(4) AUTO_INCREMENT PRIMARY KEY,
ProjectName Char(20) NOT NULL,
DepartmentName Char(30) NOT NULL,
MaxHours Int(14) NOT NULL,
StartDate Char(10) NOT NULL,
EndDate Char(10) NULL)
ENGINE=InnoDB AUTO_INCREMENT=1000;
Then type:
SET ##AUTO_INCREMENT_INCREMENT=100;
Now ProjectID is a surrogate key that starts at 1000 and increases by 100.
https://dev.mysql.com/doc/refman/5.0/en/replication-options-master.html#sysvar_auto_increment_offset
Thank you #NorbertvanNobelen !
How to insert data whenever multiple foreign keys in table
means a database which contains patient, Doctor, and staff
Patient: an appointment must be with a patient
Doctor: every appointment must have a doctor
My question how to insert data within appointment and another related table like patient, doctor at same time?
Give me an example please?
CREATE TABLE IF NOT EXISTS `doctor` (
`doctor_id` int(11) NOT NULL AUTO_INCREMENT,
`doc_name` varchar(100) NOT NULL,
`contactNum` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`qulification` varchar(100) NOT NULL,
`joiningDate` varchar(50) NOT NULL,
`u_id` int(11) NOT NULL,
PRIMARY KEY (`doctor_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
Doctor
doctor_id: 1
doctor_name : Ali
Qulification : mbbs
CREATE TABLE IF NOT EXISTS `patient` (
`patient_id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(100) NOT NULL,
`sex` varchar(11) NOT NULL,
`diagnosis` text NOT NULL,
`DOB` varchar(100) NOT NULL,
`address` varchar(200) NOT NULL,
`Contact_No` varchar(111) NOT NULL,
PRIMARY KEY (`patient_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
patient
patient_id:1
Name: Ahmed Zubair
sex: Male
diagnosis : test
DOB : 20/6/2000
address : islamabad
CREATE TABLE appointment
(
appointment_id int NOT NULL,
doctor_id int NOT NULL,
patient_id int NOT NULL,
Date int NOT NULL,
time int,
PRIMARY KEY (appointment_id),
CONSTRAINT fk_ap_pa_id FOREIGN KEY (patient_id) REFERENCES patient(patient_id),
CONSTRAINT fk_ap_do_id FOREIGN KEY (doctor_id) REFERENCES doctor (doctor_id)
);
As mentioned in the first comment, you need to first insert records into the patient and doctor tables, and then you can insert your appointment record. If these need to happen in a single operation (e.g., all succeed or all fail) then wrap the insert statements in a transaction.
I don't have a MySQL instance available to completely vet the code required, so I can't post it, but follow this process:
INSERT your doctor record
Save the primary key generated using LAST_INSERT_ID() into a local variable
INSERT your patient record
Save this primary key into a new variable using the same process as step 2
Now you can INSERT your appointment record using these two variables in the statement to ensure you satisfy the foreign keys
Again...if this is an atomic operation, then wrap these statements in a transaction that includes any validation or error checking your situation requires.
More info about LAST_INSERT_ID() here - https://stackoverflow.com/a/17112962/571237
In order to achive this you should use transaction, more detail about this you can read
First
Second
Third
Thanks
Using this two tables i'm trying to create a query to insert a new course, but i'm using a foreign key and I don't know how to pass that users(table) id into courses(table) id.
I'm trying to get something like this
I'm completely lost, on how to insert data into a table that contains a foreign key,
what i'm trying to do is:
first a person can register(user table)
2.Then the user will be available to add courses ( im using the foreign key to identify the courses for a specific user)
Users table
id | username |
---------------
1 | test |
Courses table
coursesid | coursesname | id(same id that in users table)
1 | courses test| 1
The Create Table commands are
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` char(64) COLLATE utf8_unicode_ci NOT NULL,
`salt` char(16) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
CREATE TABLE `course` (
`courseid` int(11) NOT NULL AUTO_INCREMENT,
`coursename` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`id` int(11) NOT NULL,
UNIQUE KEY (`courseid`)
FOREIGN KEY (od) REFERENCES users(id)
)
You can use subquery for find user id, e.g.:
insert into course
(courseid, coursename, id)
values
(1, 'test courses',
(SELECT id FROM users where username = 'test')
)
;
Of cause, if you know user id, you can insert directly this id:
insert into course
(courseid, coursename, id)
values
(1, 'test courses', 1)
;
Additional query for insert just last user id:
insert into course
(courseid, coursename, id)
values
(1, 'test courses',
(SELECT max(id) FROM users)
)
;