I am trying to create a table called "Borrower" or "Lånetagare" and want to insert the value from table Lån with the ID from there. The result I get is NULL. How come?
create table Lån
(
Lån_ID INT auto_increment primary key,
Lånedatum DATETIME,
Inlämningsdatum DATETIME,
Omlån DATETIME
);
INSERT INTO Lån (Lånedatum, Inlämningsdatum, Omlån)
VALUES ('2017-09-12', '2017-09-15', '2017-09-15');
CREATE TABLE Lånetagare
(
Lånetagare_ID INT(10) auto_increment primary key,
Lösenord varchar(50),
Förnamn varchar(50),
Efternamn varchar(50),
Adress varchar (50),
Ort varchar(50),
Postnummer int(5),
Email varchar(50),
Telefonnummer int(20),
Lånekort int(50),
Lån_ID int(50),
FOREIGN KEY (Lån_ID) REFERENCES Lån(Lån_ID)
);
INSERT INTO Lånetagare (Lösenord, Förnamn, Efternamn, Adress, Ort, Postnummer, Email, Telefonnummer, Lånekort)
VALUES ('hej135', 'Victor', 'Chi', 'Blekingegatan 28', 'Stockholm', 11856, 'Tim#hotmail.com', 0704582235, 56);
SELECT * FROM Lånetagare;
If you want to associate a row in Lånetagare with the previously-inserted row in Lån, you must set a value for the foreign key.
Here's a common way to do it:
INSERT INTO Lån (Lånedatum, Inlämningsdatum, Omlån)
VALUES ('2017-09-12', '2017-09-15', '2017-09-15');
INSERT INTO Lånetagare (...other columns..., Lån_ID)
VALUES (...other values..., LAST_INSERT_ID());
The LAST_INSERT_ID() function returns the most recent auto-increment id created by an INSERT statement during your session. Read more about this function here: https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id
Try
INSERT INTO Lånetagare (Lösenord, Förnamn, Efternamn, Adress, Ort, Postnummer, Email, Telefonnummer, Lånekort, Lån_ID)
VALUES ('hej135', 'Victor', 'Chi', 'Blekingegatan 28', 'Stockholm', 11856, 'Tim#hotmail.com', 0704582235, 56, (SELECT Lån_ID FROM Lån WHERE <put your select criteria here>));
Related
I am trying to create three tables using MySQL Workbench, where two columns need to be auto incremented with a fixed starting value. I have checked some online resources and figured it out what statements to use.
create database test;
use test;
/*table Project */
create table Project(
Pnumber INT NOT NULL AUTO_INCREMENT,
Pname varchar(30) NOT NULL,
Plocation enum ('QLD', 'VIC', 'NSW', 'SA') NOT NULL,
primary key(Pnumber)
);
ALTER TABLE Project AUTO_INCREMENT = 7777770;
/*table Department*/
Create table Department(
Dcode varchar(5) NOT NULL,
Dname varchar(30),
Dmg_ssn varchar(30),
primary key(Dcode)
);
/* Table Employee*/
create table Employee(
Ssn INT NOT NULL AUTO_INCREMENT,
Ename varchar(30) NOT NULL,
Bdate DATE,
Address varchar(30),
Dcode varchar(5) NOT NULL,
Driver_License varchar(30),
primary key(Ssn),
foreign key(Dcode) references Department(Dcode)
);
ALTER TABLE Employee AUTO_INCREMENT = 1000000;
/* Insert into Project*/
Insert into Project values ('7777770','Star', 'QLD');
Insert into Project values ('7777771','Innova', 'NSW');
Insert into Project values ('7777772','Andra', "QLD");
/* Insert into Department */
insert into Department values ('ABC12', 'Finances', 'RA12');
insert into Department values ('WXY10', 'Human Resources', 'RA12');
insert into Department values ('PBC32', 'S2', 'RB13');
/*Insert into Employee */
insert into Employee values ('0000001','Vladimir Rostov', '2008-7-04', '19 Wilson St', 'ABC12', '1023456');
insert into Employee values ('0000002','Rory Reid', '2002-2-10', '10 Mary St', 'WXY10', '2365947');
insert into Employee values ('0000003','Andy Murray', '2001-5-11', '1280 Albert St', 'WXY10', '5891655');
However, after I created the tables, only the column Pnumber in table Project follows the required format, while the column Ssn in Employee does not.
This is a SELECT over the Employee table:
Ssn,Ename,Bdate,Address,Dcode,Driver_License
1,"Vladimir Rostov",2008-07-04,"19 Wilson St",ABC12,1023456
2,"Rory Reid",2002-02-10,"10 Mary St",WXY10,2365947
3,"Andy Murray",2001-05-11,"1280 Albert St",WXY10,5891655
Any idea what I am doing wrong??
Your sql script has an employee table, not a student, I assume these two names refer to the same table. I will use the employee name.
So, you set the start value auto increment of the employee table to 1000000:
ALTER TABLE Employee AUTO_INCREMENT = 1000000;
But then you explicitly insert 1, 2, and 3 into this column with your insert statements because '0000001' translates into 1. If you explicitly insert a value into auto increment and it is higher than the maximum value in the given field, then mysql will insert that value as is into the auto increment field.
If you are using auto increment, then you should let it work and do not specify an explicit value:
/*Insert into Employee */
insert into Employee (Ename, Bdate, Address, Dcode, Driver_License) values ('Vladimir Rostov', '2008-7-04', '19 Wilson St', 'ABC12', '1023456');
insert into Employee (Ename, Bdate, Address, Dcode, Driver_License) values ('Rory Reid', '2002-2-10', '10 Mary St', 'WXY10', '2365947');
insert into Employee (Ename, Bdate, Address, Dcode, Driver_License) values ('Andy Murray', '2001-5-11', '1280 Albert St', 'WXY10', '5891655');
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
CREATE DATABASE Ebooks;
CREATE TABLE Usuario (
Email VARCHAR (320) PRIMARY KEY,
NombreUsuario VARCHAR (70),
Contrasena VARCHAR (20),
Nombre VARCHAR (30),
Apellido VARCHAR (30),
IdDireccion INT,
FechaNac DATE,
Sexo VARCHAR (1),
Celular BIGINT,
IdPreferencias INT,
IdTarjeta INT
);
CREATE TABLE Direccion (
IdDireccion INT PRIMARY KEY AUTO_INCREMENT,
CalleyNumero VARCHAR (120),
Colonia VARCHAR (30),
CP INT,
Ciudad VARCHAR (30),
Estado VARCHAR (20),
Pais VARCHAR (20)
);
I want to create an AFTER INSERT ON Direccion Trigger that allows me to take Direccion.IdDireccion value and insert it into Usuario.IdDireccion.
You can use the keyword NEW after inserting the value on Direccion table, for example:
DELIMITER //
CREATE TRIGGER trg_insert_usuario AFTER INSERT ON Direccion
FOR EACH ROW
BEGIN
INSERT INTO `Usuario`
VALUES('random', '1234', '1234', '6532', '12345', NEW.IdDireccion,
'123', '12', '1234', '124', '1234');
END //
DELIMITER ;
See 20.3.1 Trigger Syntax and Examples for reference.
You'll need something like:
CREATE TRIGGER ins_dir AFTER INSERT ON Direccion
FOR EACH ROW INSERT INTO Usuario SET IdDireccion=NEW.IdDireccion
Although that will insert a new row where all fields except IdDireccion are null, in particular the primary key for Usuario should be included in the INSERT statement too.
Update as per the below comment:
CREATE TRIGGER ins_dir AFTER INSERT ON Direccion
FOR EACH ROW UPDATE Usuario SET IdDireccion=NEW.IdDireccion WHERE Email=<THE EMAIL>
CREATE TABLE Editor (
UsernameID VARCHAR (30),
EditorName VARCHAR (30),
EMail VARCHAR (30),
DateOfBirth DATE,
BlogTitle VARCHAR(30),
PRIMARY KEY (UsernameID));
INSERT INTO Editor VALUES
('Mdbuzzer','Joshua', 'coker#hotmail.com', '1995-03-15', 'Nearly Bound');
INSERT INTO Editor VALUES
('Kally32','Kally', 'kally#hotmail.com', '1993-10-13', 'Tomorrows War');
SELECT * FROM Editor;
CREATE TABLE Post
(UsernameID VARCHAR (30),
PostID INT,
BlogTitle VARCHAR (30),
PostTitle VARCHAR (30),
CategoryID INT,
TimeofPost VARCHAR (20),
PRIMARY KEY(PostID),
FOREIGN KEY (UsernameID) REFERENCES Editor (UsernameID));
INSERT INTO Post VALUES
('Kally32','1','Tomorrows War', 'Mystery', '4', '12:03pm');
INSERT INTO Post VALUES
('Kally32','1','Tomorrows War', 'Let It Shine','2','10:05pm');
INSERT INTO Post VALUES
('Kally32','1','Tomorrows War','Two Can Play That Game','2', '12:00pm');
INSERT INTO Post VALUES
( 'Mdbuzzer','2','Nearly Bound', 'Goal','3', '10:05pm');
INSERT INTO Post VALUES
( 'Mdbuzzer','2','Nearly Bound','Life After Death','4', '12:03pm');
INSERT INTO Post VALUES
('Mdbuzzer','2', 'Nearly Bound','Times Up','1', '14:06pm');
SELECT * FROM Post;
Every time I try and run this script I keep getting an error saying duplicate entry '1' for key 'primary' and I don't really understand how to fix it
The problem is that you are inserting multiple rows into the POST table with a PRIMARY KEY of 1. If you are trying to implement a primary key, it must be unique.
So this:
INSERT INTO Post VALUES
('Kally32','1','Tomorrows War', 'Mystery', '4', '12:03pm');
INSERT INTO Post VALUES
('Kally32','1','Tomorrows War', 'Let It Shine','2','10:05pm');
INSERT INTO Post VALUES
('Kally32','1','Tomorrows War','Two Can Play That Game','2', '12:00pm');
INSERT INTO Post VALUES
( 'Mdbuzzer','2','Nearly Bound', 'Goal','3', '10:05pm');
INSERT INTO Post VALUES
( 'Mdbuzzer','2','Nearly Bound','Life After Death','4', '12:03pm');
INSERT INTO Post VALUES
('Mdbuzzer','2', 'Nearly Bound','Times Up','1', '14:06pm');
Could be changed to something like this:
INSERT INTO Post VALUES
('Kally32','1','Tomorrows War', 'Mystery', '4', '12:03pm');
INSERT INTO Post VALUES
('Kally32','2','Tomorrows War', 'Let It Shine','2','10:05pm');
INSERT INTO Post VALUES
('Kally32','3','Tomorrows War','Two Can Play That Game','2', '12:00pm');
If you make a column a primary key, then every value in the column must be unique. You already have one instance of '1' in the column POST_ID when you add the first tuple:
('Kally32','1','Tomorrows War', 'Mystery', '4', '12:03pm');
and if you try adding another tuple with the instance of '1' in the column POST_ID, such as:
('Kally32','1','Tomorrows War', 'Let It Shine','2','10:05pm');
you will get an error.
You have declared PostId to be the primary key of POST.
When you use insert, you should always include the columns. So, these are the first two inserts into the table:
INSERT INTO Post(UsernameID, PostID, BlogTitle, PostTitle, CategoryID, TimeofPost)
VALUES('Kally32','1','Tomorrows War', 'Let It Shine','2','10:05pm');
INSERT INTO Post(UsernameID, PostID, BlogTitle, PostTitle, CategoryID, TimeofPost)
VALUES('Kally32','1','Tomorrows War','Two Can Play That Game','2', '12:00pm');
You are setting PostId to the same value, 1, in both cases. Hence the error.
I would expect the code to look like:
CREATE TABLE Post (
UsernameID VARCHAR (30),
PostID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
BlogTitle VARCHAR (30),
PostTitle VARCHAR (30),
CategoryID INT,
TimeofPost VARCHAR (20),
FOREIGN KEY (UsernameID) REFERENCES Editor (UsernameID)
);
INSERT INTO Post(UsernameID, BlogTitle, PostTitle, CategoryID, TimeofPost)
VALUES('Kally32', 'Tomorrows War', 'Let It Shine', 2, '10:05pm');
trying to make a database for teams in a tv show here.
but when I try and insert data into tblShowteam
the following error made its appearance.
Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint 'PK__tblShowt__F693078C03317E3D'. Cannot insert duplicate key in object 'dbo.tblShowteam'.
tables
-- tabbellen aanmaken
create table tblShow(
setId int,
Datum date,
teams int
primary key (setId));
create table tblShowteam(
SetId int,
datum date,
teams int,
primary key (teams));
create table tblTeam(
TeamId int,
Coach varchar(35),
CoachId int,
teams int
primary key (CoachId));
-- participant table
create table tblDeelnemer(
DeelnemerId int identity(1, 1),
DeelnemerV varchar(35),
deelnemerT_V varchar(10),
DeelnemerA varchar(35),
CoachId int,
datum_optreden date
primary key (DeelnemerId));
--table for the public viewers
create table tblKijker(
Kijkerv varchar(35),
KijkerT_V varchar(10),
KijkerA varchar(35),
Stoelnummer int identity(1,3),
ShowId int Not null,
Email varchar(35)
primary key (Email));
my inserts would look like this:
insert into tblShowteam values (1, '2014-06-28', 1)
insert into tblShowteam values (2, '2014-06-05', 1)
insert into tblShowteam values (3, '2014-06-12', 1)
insert into tblShowteam values (4, '2014-06-19', 1)
insert into tblShowteam values (5, '2014-06-26', 1)
all other inserts (in diffrent tables) work like normal.
what am i doing wrong here?
your problem is here
primary key (teams));
i guess you have to do it like that
primary key (setId));
like that:
create table tblShowteam(
SetId int,
datum date,
teams int,
primary key (setId));
because you are inserting same teams 1 while you are using teams as primary key which means no duplicates.
your inserts:
insert into tblShowteam values (1, '2014-06-28', 1)
insert into tblShowteam values (2, '2014-06-05', 1)
...
DB translate it like this:
insert into tblShowteam (SetId, datum, teams) values (1, '2014-06-28', 1);
cause the third column is your primary key, you got this error.