MySQL INSERT INTO statement giving ERROR CODE 1062 - mysql

I have a F1 database and I'm trying to insert the team principal's name (from Principals table) into the Teams table, but for some reason it won't work. I'm not sure if my insert into statement is wrong, but I can't see why it would be. The code is below
CREATE TABLE Teams (
Team_Name VARCHAR(30) NOT NULL,
Driver_1 INT NULL,
Driver_2 INT NULL,
Nation VARCHAR(30) NOT NULL,
Seasons INT NOT NULL,
No_Titles INT NOT NULL DEFAULT 0,
Principal VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (Team_Name));
CREATE TABLE Principals (
Principal_No INT NOT NULL,
Principal_Name VARCHAR(30) UNIQUE NOT NULL,
Team VARCHAR(30) NULL,
Age INT NOT NULL,
Nationality VARCHAR(30) NOT NULL,
Seasons INT NOT NULL DEFAULT 0,
PRIMARY KEY (Principal_No),
FOREIGN KEY (Team) REFERENCES Teams(Team_Name));
Here's the insert statement. The Principals table has already been populated with the principal names and their corresponding teams
INSERT INTO Teams (Principal)
SELECT Principal_Name
FROM Principals
WHERE Team IN(
SELECT Team_Name
FROM Teams);

In your INSERT statement
INSERT INTO Teams (Principal)
-- ^
you're only inserting a value for the field Principal into the table Teams. But the Teams table has other fields as well... not inserting values into them will default them to NULL. This will lead to a contradiction in the arguments. In your Teams table:
Team_Name VARCHAR(30) NOT NULL
Nation VARCHAR(30) NOT NULL
Seasons INT NOT NULL
these fields, by definition, can't be NULL. But since no values are inserted with the INSERT statement, these will default to NULL, clashing with the definition and causing an error.
You may want to consider setting default values for the above fields or modifying your INSERT statement to accommodate those fields.
INSERT INTO Teams (Principal, Team_Name, Nation, Seasons)
SELECT
-- four columns ...

Your insert statement tries to assign null values to columns that have 'not null' property. Check these columns 'not null' -> false or assign default value or define values in your insert statement. I hope this help

Related

Selecting data from other table using a foreign key?

So I'm trying to get the clan tag from ranks table for a specific member_id. But I don't understand how to do that. I used INNER JOIN commands but nothing works.
CREATE TABLE ranks(
rank VARCHAR(8),
tag VARCHAR(18) NOT NULL,
PRIMARY KEY(rank)
);
CREATE TABLE member(
member_id INT UNSIGNED AUTO_INCREMENT,
first_name VARCHAR(15) NOT NULL,
last_name VARCHAR(15),
ign VARCHAR(20) NOT NULL,
rank VARCHAR(8) NOT NULL,
joined_date DATE NOT NULL,
dob DATE,
sex ENUM('M','F') NOT NULL,
country VARCHAR(3) NOT NULL,
PRIMARY KEY(member_id),
FOREIGN KEY(rank) REFERENCES ranks(rank)
);
INSERT INTO ranks VALUES
('Founder','|NoMercy|King'),
('Admin','^1|NoMercy|^7'),
('TmpAdmin','^5|NoMercy|^7'),
('Pro','^1|NoMercy PRO|^7'),
('Member','^4|NoMercy|^7'),
('Banned','BANNED');
INSERT INTO member VALUES
(NULL,'Reznov','NULL','REZ','Member','2017/12/22','1954/02/28','M','RUS'),
(NULL,'Amanda','NULL','S3XXY|G!RL|','Pro','2018/01/05','1992/01/25','F','USA'),
(NULL,'Elmasri','Navathe','INDIAN_Noob _XOX','TmpAdmin','2018/04/02','1960/08/25','M','IND'),
(NULL,'Tony','Silva','Cool KiD','Member','2018/04/26','1988/02/22','M','BR'),
(NULL,'Hashan','NULL','Big Papa','Member','2018/05/08','1996/06/12','M','NZ'),
(NULL,'Emma','Watson','EmmaXXX','Banned','2018/06/10','1985/05/22','F','UK');
I need to output the correct tag for specific member. It should only display the tag.
Please help!
below query should be worked
SELECT tag FROM ranks INNER JOIN member ON ranks.rank=member.rank
where member_id=1;
http://www.sqlfiddle.com/#!9/e90392/1
tag
^4|NoMercy|^7

Update row in first table and insert a row into a second table in a single query

I'm trying to figure it out how to insert a row into a table on updating a particular field in the second table.
Let's say I have table 1 (dif):
CREATE TABLE dif
(
Position INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
pKey SMALLINT(3) UNSIGNED NOT NULL,
Number SMALLINT(3) UNSIGNED DEFAULT 0 NOT NULL
);
ALTER TABLE dif
ADD CONSTRAINT dif_article_pKey_fk
FOREIGN KEY (pKey) REFERENCES article (pKey) ON UPDATE CASCADE;
and table 2 (article):
CREATE TABLE IF NOT EXISTS article (
pKey smallint(3) unsigned NOT NULL AUTO_INCREMENT,
Name varchar(80) COLLATE utf8_roman_ci NOT NULL,
Number SMALLINT NOT NULL DEFAULT 0
PRIMARY KEY (pKey)
);
The table article is populated with some data and should be only updated. Table "dif" is empty at the beginning. So, let's say I'm updating the fields on "article" like this:
UPDATE article SET pKey = 15, Name = SomeName, Number = 22 WHERE pKey=15;
Can I somehow combine the UPDATE query with this?
INSERT INTO dif (pKey, Number) VALUES (15, 12);
The "12" is the difference between the "article.Number" before and after UPDATE.
No, but you can make a stored procedure that does both of those things and then execute it in a single statement.
create procedure GiveThisABetterName
(
in pKey int,
in newNumber int,
in currentNumber int,
in newName varchar(100)
)
begin
update
article
set
Name = newName, Number = newNumber
where
pKey = pKey;
insert into dif (pKey, Number) values (pKey, newNumber);
end
My mysql syntax is rusty, but that should be close. Then when you want to execute it:
call GiveThisABetterName(12, 15, 22, 'Some Name');
EDIT: After reading your question again, it seems to me that you're trying to make your data model track audit information that it's just not set up to accommodate naturally. Do you have control over the model? If so, consider something like this (see here for a working example of what's below):
CREATE TABLE IF NOT EXISTS article (
pKey smallint(3) unsigned NOT NULL AUTO_INCREMENT,
Name varchar(80) COLLATE utf8_roman_ci NOT NULL,
PRIMARY KEY (pKey)
);
CREATE TABLE ArticleNumbers
(
Counter int UNSIGNED PRIMARY KEY AUTO_INCREMENT,
pKey SMALLINT(3) UNSIGNED NOT NULL,
Number SMALLINT(3) DEFAULT 0 NOT NULL,
Difference SMALLINT(3)
);
ALTER TABLE ArticleNumbers
ADD CONSTRAINT ArticleNumbers_article_pKey_fk
FOREIGN KEY (pKey) REFERENCES article (pKey) ON UPDATE CASCADE;
Maybe add a few views to make things easier:
CREATE VIEW GroupedArticleNumbers
as
select pKey, max(Counter) as Counter
from ArticleNumbers
group by pKey;
CREATE VIEW CurrentArticles
as
select article.pKey, article.Name, numbers.Number, numbers.Difference
from article
left outer join GroupedArticleNumbers filter on article.pKey = filter.pKey
left outer join ArticleNumbers numbers on filter.Counter = numbers.Counter;
Since you can track the number separately from the base record now but still easily determine what the current number is, you can now combine your update and insert statement functionality. See below.
First, some test data:
insert into article (Name) values ('Test');
insert into ArticleNumbers (pKey, Number, Difference) values (1, 10, null);
insert into ArticleNumbers (pKey, Number, Difference) select 1, 20, 20 - Number from CurrentArticles where pKey = 1;
insert into ArticleNumbers (pKey, Number, Difference) select 1, 50, 50 - Number from CurrentArticles where pKey = 1;
insert into ArticleNumbers (pKey, Number, Difference) select 1, 15, 15 - Number from CurrentArticles where pKey = 1;
See how nicely that works out once the overhead of setting up the schema has been done?
To get the current number for the article we created:
select * from currentarticles where pKey = 1
To get the number history for that article:
select * from article
left outer join articlenumbers on article.pkey = articlenumbers.pkey
order by counter asc
If you're willing to mess with your data model, you can have an alternative to stored procedures.
Alternatively, if you want to use triggers as #Jonathan Leffler suggested, something like this should work:
CREATE TABLE article (
pKey smallint(3) unsigned NOT NULL AUTO_INCREMENT,
Name varchar(80) COLLATE utf8_roman_ci NOT NULL,
Number SMALLINT(3) DEFAULT 0 NOT NULL,
PRIMARY KEY (pKey)
);
CREATE TABLE ArticleNumbers
(
Counter int UNSIGNED PRIMARY KEY AUTO_INCREMENT,
pKey SMALLINT(3) UNSIGNED NOT NULL,
Number SMALLINT(3) DEFAULT 0 NOT NULL,
Difference SMALLINT(3)
);
delimiter $
create trigger tr_u_article
before update on article
for each row
begin
insert into ArticleNumbers (pKey, Number, Difference) select old.pKey, new.Number, new.Number - old.Number
end;
delimiter ;

Auto_increment trigger

I need to auto_increment the primary key in a mysql database using a trigger. Unfortunately, I am not quite sure how to do this. In the sample code I have provided, I need the employee table primary key to auto_increment beginning with an empty table and a starting value of 200. Then, I need each new insert to increment by 1.Thanks for looking and I hope you are able to help me.
CREATE TABLE department (
dept_name VARCHAR(50) NOT NULL Primary Key
);
CREATE TABLE employee (
emp_id INT(6) unsigned Default 0 Not NULL
, last_name VARCHAR(25) NOT NULL
, first_name VARCHAR(40) NOT NULL
, dept_name VARCHAR(50) NOT NULL
, PRIMARY KEY(emp_id, dept_name)
, FOREIGN KEY(dept_name) REFERENCES department (dept_name)
);
There are several things you need to do:
Declare the emp_id column as AUTO_INCREMENT;
Set the value of AUTO_INCREMENT property of the table to 200;
Do not provide any value for column emp_id when you INSERT rows in table employee.
Change the table creation as below:
CREATE TABLE employee (
emp_id INT(6) UNSIGNED NOT NULL AUTO_INCREMENT,
last_name VARCHAR(25) NOT NULL,
first_name VARCHAR(40) NOT NULL,
dept_name varchar(50) NOT NULL
PRIMARY KEY(emp_id),
FOREIGN KEY(dept_name) REFERENCES department_tbl(dept_name)
) AUTO_INCREMENT=200;
If the table has an AUTO_INCREMENT column then it must be the PRIMARY KEY of the table. I removed dept_name from the definition of the PK above. I also removed the default value 0 from the emp_id column. It's default value is generated by MySQL using the AUTO_INCREMENT policy.
When you INSERT a new record into the employee table all you have to do is to not provide any value for the emp_id column:
INSERT INTO employee (last_name, first_name, dept_name)
VALUES ('Doe', 'John', 'accounting');
Then use the LAST_INSERT_ID() MySQL function to retrieve the value of the emp_id generated on insertion.
The language or the library you use to develop the client application probably has a function that wraps LAST_INSERT_ID() and returns its value.

insert query is not working for the row which has a foreign key

I am trying to learn foreign key constraint so far i have been able to create foreign keys in mysql
Here is my create table query for three tables:
create table customer(
CustId int(100) not null AUTO_INCREMENT primary key,
FirstName varchar(300) default null,
LastName varchar(300) default null,
Gender varchar(200) default null,
Category varchar(200) default null,
DateOfBirth varchar(200) default null,
Age int(3)default null
);
create table address(
Address_Id int(100) not null AUTO_INCREMENT primary key,
Address varchar(1000) default null,
Country varchar(500) default null,
State varchar (500) default null,
city varchar(500)default null,
PinCode int(10)default null,
CustId int(100) not null,
foreign key(CustId) references customer(CustId)
);
create table contact(
Contact_Id int(100) not null AUTO_INCREMENT primary key,
EmailId varchar(500)default null,
ContactNo varchar(20) default null,
MobileNo varchar(20) default null,
CustId int(100) not null,
Address_Id int(100) not null,
foreign key(CustId) references customer(CustId),
foreign key(Address_Id) references address(Address_Id)
);
K now i got it till here :
START TRANSACTION;
SET #lid := null;
insert into customer (FirstName,LastName,Gender,Category,DateOfBirth,Age)values('Ashok','sharma','Male','Affiliate','1988-04-17','26');
SELECT LAST_INSERT_ID() INTO #lid;
insert into address(CustId, Address,Country,State,city,Pincode)values (#lid, 'No.1645','India','Karnataka','Bangalore','560060');
COMMIT;
Using transaction and commit was the solution but how to do it for contact table where i have too foreign keys. And i need to get two auto incremented values.
Please guide me on this as well.
You do this in multiple statements:
START TRANSACTION;
SET #lid := null;
insert into customer (FirstName,LastName,Gender,Category,DateOfBirth,Age)values('Ashok','sharma','Male','Affiliate','1988-04-17','26');
SELECT LAST_INSERT_ID() INTO #lid;
insert into address(CustId, Address,Country,State,city,Pincode)values (#lid, 'No.1645','India','Karnataka','Bangalore','560060');
COMMIT;
For MySQL 5.1.12 and later, with no argument, LAST_INSERT_ID() returns a 64-bit value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement.
This is session bound, so don't worry, that another session messes up your last_insert_id or something. Read more about it here.
And you better put it all in a transaction like I did. This makes sure, that all statements succeed or none, not just parts of them. You have to use InnoDB for it though. MyISAM does not support this. Or you live with the risk :) But since you use foreign keys I assume you use InnoDB, just wanted to mention it for completeness.
The variable I used can of course be replaced with a PHP variable. Or you do it like this:
START TRANSACTION;
insert into customer (FirstName,LastName,Gender,Category,DateOfBirth,Age)values('Ashok','sharma','Male','Affiliate','1988-04-17','26');
SELECT LAST_INSERT_ID() INTO #lid;
insert into address(CustId, Address,Country,State,city,Pincode)
SELECT #lid, 'No.1645','India','Karnataka','Bangalore','560060';
COMMIT;
EDIT:
START TRANSACTION;
SET #lid_c := null;
SET #lid_a := null;
insert into customer (FirstName,LastName,Gender,Category,DateOfBirth,Age)values('Ashok','sharma','Male','Affiliate','1988-04-17','26');
SELECT LAST_INSERT_ID() INTO #lid_c;
insert into address(CustId, Address,Country,State,city,Pincode)values (#lid, 'No.1645','India','Karnataka','Bangalore','560060');
SELECT LAST_INSERT_ID() INTO #lid_a;
INSERT INTO contact (CustId, Address_Id, another_column) VALUES
(#lid_c, #lid_a, 'another_value');
COMMIT;

Sql inserting information into several items in a table

I got this example to work with some help on here:
http://sqlfiddle.com/#!2/92e87/1
However, if I want to try and insert information for every child of the table, I cant seem to get it to work (using this code):
CREATE TABLE country (
id integer NOT NULL PRIMARY KEY AUTO_INCREMENT,
name varchar(255) NOT NULL
)
;
CREATE TABLE location (
id integer NOT NULL PRIMARY KEY AUTO_INCREMENT,
name varchar(255) NOT NULL,
coordinate varchar(255) NOT NULL,
country_id integer NOT NULL REFERENCES country (id)
)
;
CREATE TABLE item (
id integer NOT NULL PRIMARY KEY AUTO_INCREMENT,
title varchar(60) NOT NULL,
description varchar(900) NOT NULL,
date datetime NOT NULL,
source varchar(255) NOT NULL,
link varchar(255) NOT NULL,
location_id integer NOT NULL REFERENCES location (id)
)
;
Insert Into item (title) values ('Title');
Insert Into item (description) values ('Description');
Insert Into item (date) values ('1995-12-31T23:59:59Z');
Insert Into item (source) values ('Source');
Insert Into item (link) values ('Link');
Insert Into item (location_id) values ('1');
Is this the correct way of doing this? Secondly, it tells me "description" doesnt have a default value, but does it need one if I will always be putting information into it?
Thank you for any help you can give
Insert Into item (title, description, date, source, link, location_id)
values ('Title', 'Description','1995-12-31T23:59:59Z','source','Link',1);
Each insert acts as inserting a new record. hence you need to combine all data into one insert statement as given above.
The SQL asks for default value, because you have mentioned NOT NULL in the table definition which you have created.
For every insert, you will end up with a new row of data in the item table. I do not think this is what you want. Instead, do:
INSERT INTO item VALUES (NULL, [title], [description], [date], [source], [link], [location_id]);
Replace the items in [ and ] with the appropriate values.
You are being told that Description does not have a default value because in your INSERT statements that don't specify a value for that column, there is no default value that the database can fill in for that field.