SQL error: 1364 Field 'XXXX' doesn't have a default value - mysql

So I have, table courses:
CREATE TABLE IF NOT EXISTS `AppDziennik`.`courses` (
`id_course` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(80) NOT NULL ,
`teachers_id_teacher` INT NOT NULL ,
`end_date` DATE NULL ,
`about` VARCHAR(255) NULL ,
`start_date` DATE NULL ,
PRIMARY KEY (`id_course`) ,
UNIQUE INDEX `id_course_UNIQUE` (`id_course` ASC) ,
CONSTRAINT `fk_courses_teachers1`
FOREIGN KEY (`teachers_id_teacher` )
REFERENCES `AppDziennik`.`teachers` (`id_teacher` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
and second table
CREATE TABLE IF NOT EXISTS `AppDziennik`.`teachers` (
`id_teacher` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NOT NULL ,
`surname` VARCHAR(45) NOT NULL ,
`about` VARCHAR(255) NULL ,
`id_class` INT NULL ,
`rank` VARCHAR(45) NULL ,
`logins_id_login` INT NOT NULL ,
PRIMARY KEY (`id_teacher`) ,
INDEX `fk_teachers_classes1_idx` (`id_class` ASC) ,
INDEX `fk_teachers_logins1_idx` (`logins_id_login` ASC) ,
CONSTRAINT `fk_teachers_classes1`
FOREIGN KEY (`id_class` )
REFERENCES `AppDziennik`.`classes` (`id_class` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_teachers_logins1`
FOREIGN KEY (`logins_id_login` )
REFERENCES `AppDziennik`.`logins` (`id_login` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
When I make that insert
insert into appdziennik.courses
(name, id_teacher, about, start_date, end_date)
values ("Math",'7',"Math",'2013-08-01','2014-06-29');
I get that error:
Error Code: 1364. Field 'teachers_id_teacher' doesn't have a default
value
Where I made mistake? How i could fix it.

If you're sending an INSERT to table courses, there is no field id_teacher (you want teachers_id_teacher). Since you're using a foreign key, that key must exist in table teachers before you INSERT a record into table courses. Also, you should only be using backticks (`) and single quotes (') in all your statements.

you are trying to insert into the courses table for the column id_teacher a value but your not inserting a value for the column teachers_id_teacher. so I would propose to make the statement as followed:
insert into appdziennik.courses (name, teachers_id_teacher, about, start_date, end_date) values ("Math",'7',"Math",'2013-08-01','2014-06-29');
Sarajog

Related

MySQL: Calculate value and set when triggered by an INSERT in another table

Quick intro: I am trying to make a program that would allow me and my friends to keep track of who ows who money. Right now I am working on the database.
I am testing it on this website.
CREATE TABLE `payments`
(
`payment_id` integer NOT NULL AUTO_INCREMENT ,
`title` varchar(200) NOT NULL ,
`descrp` tinytext NULL ,
`room_id` integer NOT NULL ,
`u_from` integer NOT NULL ,
`u_to` integer NOT NULL ,
`value` decimal DEFAULT 0, CHECK (value>=0),
PRIMARY KEY (`payment_id`),
KEY `fkIdx_39` (`u_from`),
CONSTRAINT `FK_38` FOREIGN KEY `fkIdx_39` (`u_from`) REFERENCES `users` (`user_id`),
KEY `fkIdx_42` (`u_to`),
CONSTRAINT `FK_41` FOREIGN KEY `fkIdx_42` (`u_to`) REFERENCES `users` (`user_id`),
KEY `fkIdx_51` (`room_id`),
CONSTRAINT `FK_50` FOREIGN KEY `fkIdx_51` (`room_id`) REFERENCES `rooms` (`room_id`)
);
CREATE TABLE `rooms`
(
`room_id` integer NOT NULL AUTO_INCREMENT ,
`web_link` varchar(30) NOT NULL ,
`name` varchar(200) NOT NULL ,
`descrp` tinytext,
PRIMARY KEY (`room_id`)
);
CREATE TABLE `user_room`
(
`id` integer NOT NULL AUTO_INCREMENT ,
`user_id` integer NOT NULL ,
`room_id` integer NOT NULL ,
`user_role` varchar(200) DEFAULT "standard" ,
`cash` decimal NOT NULL DEFAULT 0 ,
PRIMARY KEY (`id`),
KEY `fkIdx_16` (`user_id`),
CONSTRAINT `FK_15` FOREIGN KEY `fkIdx_16` (`user_id`) REFERENCES `users` (`user_id`),
KEY `fkIdx_36` (`room_id`),
CONSTRAINT `FK_35` FOREIGN KEY `fkIdx_36` (`room_id`) REFERENCES `rooms` (`room_id`)
);
CREATE TABLE `users`
(
`user_id` integer NOT NULL AUTO_INCREMENT ,
`login` varchar(50) NOT NULL ,
`display_name` varchar(100) NULL ,
PRIMARY KEY (`user_id`)
);
DELIMITER //
CREATE TRIGGER after_new_payment_sum_cash
AFTER INSERT ON payments FOR EACH ROW
BEGIN
DECLARE user_from_cash decimal;
DECLARE user_to_cash decimal;
SET #user_from_cash := (SELECT cash FROM user_room WHERE user_id = NEW.u_from);
SET #user_to_cash := (SELECT cash FROM user_room WHERE user_id = NEW.u_to);
UPDATE user_room SET cash = (user_from_cash - NEW.value) WHERE user_id = NEW.u_from;
UPDATE user_room SET cash = (user_to_cash + NEW.value) WHERE user_id = NEW.u_to;
END //
DELIMITER ;
INSERT INTO users (login, display_name) VALUES ("kacper1", "Kacper2");
INSERT INTO users (login, display_name) VALUES ("kacper2", "Kacper2");
INSERT INTO rooms (web_link, name, descrp) VALUES ('xx', 'room1', 'description');
INSERT INTO user_room (user_id, room_id) VALUES ((SELECT user_id FROM users WHERE login='kacper1'),
(SELECT room_id FROM rooms WHERE name ='room1'));
INSERT INTO user_room (user_id, room_id) VALUES ((SELECT user_id FROM users WHERE login='kacper2'),
(SELECT room_id FROM rooms WHERE name ='room1'));
select * from users;
select * from rooms;
select * from user_room;
select * from payments;
INSERT INTO payments (title, descrp, room_id, u_from, u_to, value) VALUES ('plat1', 'plat1 desc', 1, 1, 2, 10);
select * from user_room;
As you can see by yourself I get this error: ERROR 1048 (23000) at line 88: Column 'cash' cannot be null
The purpose of the trigger is to calculate the cash filed in user_room table for user_from and user_to and keep it constantly updated.
As far as I understand this, one of the SET... lines is giving this error.
The formula user_from_cash - NEW.value becomes NULL as it should be #user_from_cash.
Further improvement:
You better use local variables inside the trigger (not #var)
DECIMAL-datatype should have length defined.

create a trigger that adds a field to +5 and creates the total in another table

I'm new and I'm not so good with the triggers, I place the tables and figure out how to create this sum
-- Table `databasestreaming`.`tipologiaabbonamento`
CREATE TABLE IF NOT EXISTS `databasestreaming`.`tipologiaabbonamento` (
`idtipologiaabbonamento` INT NOT NULL AUTO_INCREMENT,
`piano abbonamento` VARCHAR(45) NULL,
`dispositivi` VARCHAR(45) NULL,
`Risoluzione` VARCHAR(45) NULL,
`Prezzo` INT NULL,
PRIMARY KEY (`idtipologiaabbonamento`))
ENGINE = InnoDB;
-- Table databasestreaming.abbonamento
CREATE TABLE IF NOT EXISTS `databasestreaming`.`abbonamento` (
`idabbonamento` INT NOT NULL AUTO_INCREMENT,
`data attivazione` DATE NULL,
`data termine` DATE NULL,
`Sport` ENUM("Si", "No") NULL,
`cliente_idcliente` INT NOT NULL,
`tipologiaabbonamento_idtipologiaabbonamento` INT NOT NULL,
`Prezzo_finale` INT NULL,
PRIMARY KEY (`idabbonamento`, `cliente_idcliente`, `tipologiaabbonamento_idtipologiaabbonamento`),
INDEX `fk_abbonamento_cliente_idx` (`cliente_idcliente` ASC) ,
INDEX `fk_abbonamento_tipologiaabbonamento1_idx` (`tipologiaabbonamento_idtipologiaabbonamento` ASC) ,
CONSTRAINT `fk_abbonamento_cliente`
FOREIGN KEY (`cliente_idcliente`)
REFERENCES `databasestreaming`.`cliente` (`idcliente`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_abbonamento_tipologiaabbonamento1`
FOREIGN KEY (`tipologiaabbonamento_idtipologiaabbonamento`)
REFERENCES `databasestreaming`.`tipologiaabbonamento` (`idtipologiaabbonamento`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I would like that when the user selects from enum Si with Sport, the trigger will take the price from the type of subscription (three types of subscriptions that will choose the user) and add the type of subscription chosen to the eventual or not of the sport choice, if yes, then we add +5 if instead it chooses no, in the final price I would like it to simply report the price of the chosen subscription

MySQL: "CREATE DATABASE" results in MySQL Error Code: 1064

I recently bought this book called "SQL Queries for Mere Mortals (3rd Edition" to study SQL. It came with MySQL scripts that they said I could run and have example databases to work with and follow along with the book. However, some of the scripts are resulting in an error message. Here is one example script that will not work:
CREATE DATABASE EntertainmentAgencyModify;
USE EntertainmentAgencyModify;
CREATE TABLE Agents (
AgentID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
AgtFirstName nvarchar (25) NULL ,
AgtLastName nvarchar (25) NULL ,
AgtStreetAddress nvarchar (50) NULL ,
AgtCity nvarchar (30) NULL ,
AgtState nvarchar (2) NULL ,
AgtZipCode nvarchar (10) NULL ,
AgtPhoneNumber nvarchar (15) NULL ,
DateHired date NULL ,
Salary decimal(15, 2) NULL DEFAULT 0 ,
CommissionRate float(24) NULL
);
CREATE TABLE Customers (
CustomerID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
CustFirstName nvarchar (25) NULL ,
CustLastName nvarchar (25) NULL ,
CustStreetAddress nvarchar (50) NULL ,
CustCity nvarchar (30) NULL ,
CustState nvarchar (2) NULL ,
CustZipCode nvarchar (10) NULL ,
CustPhoneNumber nvarchar (15) NULL
);
CREATE TABLE Engagements (
EngagementNumber int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StartDate date NULL ,
EndDate date NULL ,
StartTime time NULL ,
StopTime time NULL ,
ContractPrice decimal(15,2) NULL DEFAULT 0 ,
CustomerID int NULL DEFAULT 0 ,
AgentID int NULL DEFAULT 0 ,
EntertainerID int NULL DEFAULT 0
);
CREATE TABLE Engagements_Archive (
EngagementNumber int NOT NULL ,
StartDate date NULL ,
EndDate date NULL ,
StartTime time NULL ,
StopTime time NULL ,
ContractPrice decimal(15,2) NULL ,
CustomerID int NULL ,
AgentID int NULL ,
EntertainerID int NULL
);
CREATE TABLE Entertainer_Members (
EntertainerID int NOT NULL ,
MemberID int NOT NULL DEFAULT 0 ,
Status smallint NULL DEFAULT 0
);
CREATE TABLE Entertainer_Styles (
EntertainerID int NOT NULL ,
StyleID int NOT NULL DEFAULT 0
);
CREATE TABLE Entertainers (
EntertainerID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
EntStageName nvarchar (50) NULL ,
EntSSN nvarchar (12) NULL ,
EntStreetAddress nvarchar (50) NULL ,
EntCity nvarchar (30) NULL ,
EntState nvarchar (2) NULL ,
EntZipCode nvarchar (10) NULL ,
EntPhoneNumber nvarchar (15) NULL ,
EntWebPage nvarchar (50) NULL ,
EntEMailAddress nvarchar (50) NULL ,
DateEntered date NULL ,
EntPricePerDay decimal(15,2) NULL
);
CREATE TABLE Members (
MemberID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
MbrFirstName nvarchar (25) NULL ,
MbrLastName nvarchar (25) NULL ,
MbrPhoneNumber nvarchar (15) NULL ,
Gender nvarchar (2) NULL
);
CREATE TABLE Musical_Preferences (
CustomerID int NOT NULL DEFAULT 0 ,
StyleID int NOT NULL DEFAULT 0
);
CREATE TABLE Musical_Styles (
StyleID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StyleName nvarchar (75) NULL
);
CREATE INDEX AgtZipCode ON Agents(AgtZipCode);
CREATE INDEX CustZipCode ON Customers(CustZipCode);
CREATE INDEX AgentsEngagements ON Engagements(AgentID);
CREATE INDEX CustomerID ON Engagements(CustomerID);
CREATE INDEX EmployeeID ON Engagements(AgentID);
CREATE INDEX EntertainerID ON Engagements(EntertainerID);
ALTER TABLE Engagements_Archive
ADD CONSTRAINT Engagements_Archive_PK PRIMARY KEY
(
EngagementNumber
);
CREATE INDEX CustomerID ON Engagements_Archive(CustomerID);
CREATE INDEX EmployeeID ON Engagements_Archive(AgentID);
CREATE INDEX EntertainerID ON Engagements_Archive(EntertainerID);
ALTER TABLE Entertainer_Members
ADD CONSTRAINT Entertainer_Members_PK PRIMARY KEY
(
EntertainerID,
MemberID
);
CREATE INDEX EntertainersEntertainer_Members ON Entertainer_Members(EntertainerID);
CREATE INDEX MembersEntertainer_Members ON Entertainer_Members(MemberID);
ALTER TABLE Entertainer_Styles
ADD CONSTRAINT Entertainer_Styles_PK PRIMARY KEY
(
EntertainerID,
StyleID
);
CREATE INDEX EntertainersEntertainer_Styles ON Entertainer_Styles(EntertainerID);
CREATE INDEX Musical_StylesEntertainer_Styles ON Entertainer_Styles(StyleID);
CREATE INDEX EntZipCode ON Entertainers(EntZipCode);
ALTER TABLE Musical_Preferences
ADD CONSTRAINT Musical_Preferences_PK PRIMARY KEY
(
CustomerID,
StyleID
);
CREATE INDEX CustomerID ON Musical_Preferences(CustomerID);
CREATE INDEX StyleID ON Musical_Preferences(StyleID);
ALTER TABLE Engagements
ADD CONSTRAINT Engagements_FK00 FOREIGN KEY
(
AgentID
) REFERENCES Agents (
AgentID
),
ADD CONSTRAINT Engagements_FK01 FOREIGN KEY
(
CustomerID
) REFERENCES Customers (
CustomerID
),
ADD CONSTRAINT Engagements_FK02 FOREIGN KEY
(
EntertainerID
) REFERENCES Entertainers (
EntertainerID
);
ALTER TABLE Entertainer_Members
ADD CONSTRAINT Entertainer_Members_FK00 FOREIGN KEY
(
EntertainerID
) REFERENCES Entertainers (
EntertainerID
),
ADD CONSTRAINT Entertainer_Members_FK01 FOREIGN KEY
(
MemberID
) REFERENCES Members (
MemberID
);
ALTER TABLE Entertainer_Styles
ADD CONSTRAINT Entertainer_Styles_FK00 FOREIGN KEY
(
EntertainerID
) REFERENCES Entertainers (
EntertainerID
) ON DELETE CASCADE,
ADD CONSTRAINT Entertainer_Styles_FK01 FOREIGN KEY
(
StyleID
) REFERENCES Musical_Styles
(
StyleID
);
ALTER TABLE Musical_Preferences
ADD CONSTRAINT Musical_Preferences_FK00 FOREIGN KEY
(
CustomerID
) REFERENCES Customers (
CustomerID
) ON DELETE CASCADE,
ADD CONSTRAINT Musical_Preferences_FK01 FOREIGN KEY
(
StyleID
) REFERENCES Musical_Styles (
StyleID
);
Running this script results in the following error message:
16:33:35 CREATE DATABASE EntertainmentAgencyModify Error Code: 1064.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'CREATE DATABASE EntertainmentAgencyModify' at line 1 0.00041
sec
Screenshot
I have tried running other scripts that came with the book that also starts with "CREATE DATABASE" and some of them ran smoothly without any errors, so I'm confused as to why I'm getting this error message. Any help would be greatly appreciated! Thanks all!
Note that since this script has a "CREATE DATABASE" at the top it will fail if that database already exists. That also means that if it works partially and you run it again, it;ll fail completely the next time. "CREATE DATABASE" is a pretty big hammer, so you probably don't want to get into the habit of doing it a lot. But, having said that, here's an even bigger hammer; add
DROP DATABASE IF EXISTS EntertainmentAgencyModify;
in front of the CREATE and similarly for the others. When you have real data, you, of course, never want to use either of these.
Can you try running the following just by typing it in your mysql console:
CREATE DATABASE EntertainmentAgencyModify;
It should simply work, or at least tell you something more then a syntax error.
The code executes fine. May be its a problem with your MySql.
Try to install a new MySql. :)
https://www.mysql.com/downloads/
Thanks everyone! I have no idea why this works, but I found a solution. I had to simply delete "CREATE " from the first line of the script and re-type it. Then it worked. If anyone has any idea why this seemingly irrelevant solution worked, I'd love to know. Thanks everyone for your help!

How to Add integer column to an String column in MySQl 5.0

I Want to add an Integer Column to a String that's because i need to generate a varchar variable with a numeric part that automatically increments. For example, P000001,P000002...
In order to do that what i am doing while creation of table i have taken an int field ID which auto_increments and i am Concatenating P with 00000 and the ID value
The Table i have created is :
CREATE TABLE tblAcceptTest(
ID int AUTO_INCREMENT NOT NULL primary key,
PatientID as CONCAT('P' , CONCAT('000000',CAST(ID as char)))
);
It Shows me the error from as keyword.
Please help
MySQL's documentation (http://dev.mysql.com/doc/refman/5.1/en/create-table.html) says, "the default value must be a constant; it cannot be a function or an expression." Why don't you just get the PatientID value afterward as part of the SELECT:
SELECT CONCAT('P', LPAD(ID, 6, 0)) AS PatientID FROM tblAcceptTest;
It looks like you want six digits after the "P", so try this for your expression:
CONCAT('P', LPAD(ID, 6, '0'))
Mysql has little support for computed columns.
Patient ID from your specification could be a char(7)
CREATE TABLE tblAcceptTest(
ID int AUTO_INCREMENT NOT NULL primary key,
PatientID char(7)
);
Then create some triggers. Note that the following insert trigger will cause issues with high concurrency servers.
DELIMITER |
CREATE TRIGGER tblAcceptTest_insert BEFORE INSERT ON tblAcceptTest
FOR EACH ROW BEGIN
DECLARE next_id INT;
SET next_id = (SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='tblAcceptTest');
SET NEW.PatientID = CONCAT('P' , RIGHT(CONCAT('000000',next_id),6)) ;
END;
|
CREATE TRIGGER tblAcceptTest_update BEFORE UPDATE ON tblAcceptTest
FOR EACH ROW BEGIN
SET NEW.PatientID = CONCAT('P' , RIGHT(CONCAT('000000',NEW.ID),6)) ;
END;
|
DELIMITER ;
You use relationships and views to achieve the same result.
CREATE TABLE `patient` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`patient` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `accepted_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`patient_id` int(11) NOT NULL,
`accepted` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `patient_id` (`patient_id`),
CONSTRAINT `accepted_test_ibfk_1` FOREIGN KEY (`patient_id`) REFERENCES `patient` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create or replace view accepted_test_veiw as
select CONCAT('P' , RIGHT(CONCAT('000000',patient_id),6)) patient_key
, accepted
, id accepted_test_id
, patient_id
from accepted_test ;
select * from `accepted_test_veiw`

ON DUPLICATE KEY UPDATE refuses to update

Having some troubles with ON DUPLICATE KEY UPDATE in MySQL. Below is the query im trying to run.
INSERT INTO `Overall` ( `rsn` , `starting_xp` , `starting_lvl` ) VALUES ( 'iWader' , '195843626' , '2281' ) ON DUPLICATE KEY UPDATE `current_xp` = '195843626' AND `current_lvl` = '2281'
It inserts fine, but when there is a duplicate it doesnt update, and doesnt throw any errors.
Running the query through PMA returns no error and doesnt update
Removing the ON DUPLICATE KEY UPDATE section returns a duplicate key error
This is the structure of my table
CREATE TABLE IF NOT EXISTS `overall` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rsn` varchar(12) NOT NULL,
`starting_xp` int(10) unsigned NOT NULL,
`starting_lvl` int(10) unsigned NOT NULL,
`current_xp` int(10) unsigned NOT NULL,
`current_lvl` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `rsn` (`rsn`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
After ON DUPLICATE KEY UPDATE you should not need to use and with the fields, use , instead.
ON DUPLICATE KEY UPDATE `current_xp` = '195843626', `current_lvl` = '2281'
Try this:
INSERT INTO `Overall` ( `rsn` , `starting_xp` , `starting_lvl` ) VALUES ( 'iWader' , '195843626' , '2281' ) ON DUPLICATE KEY UPDATE `current_xp` = '195843626', `current_lvl` = '2281';
The AND in your UPDATE clause is wrong. The AND is used in boolean expressions like "is foo true AND bar true?"
Here you want to update column current_xp, current_lvl.