SQL Insert with AUTO INCREMENT - mysql

I am trying to insert 50 values into a DB, the table has two column names, one is an ID column set to auto increment and the other is for a code.
When I attempt to do the insert I get a error.
This is my SQL code:
INSERT INTO Names (Id, Code)
VALUES (NULL, 'CodeHere', NULL, 'CodeHere', NULL, 'CodeHERE' );

Don't include the ID column if it is auto increment and split the input to one one value per time
INSERT INTO Names (Code)
VALUES ('CodeHere'),('CodeHere'),('CodeHERE' );

INSERT INTO Names VALUES ('CodeHere'),('2CodeHere'),('3CodeHere'),('4CodeHere')
just ignore auto increment column.

Use this
INSERT INTO Names (Id, Code)
VALUES (NULL, 'CodeHere'), (NULL, 'CodeHere') ,( NULL, 'CodeHERE' );

Related

Insert a line with different values

CREATE TABLE `playersrb` (
`position` numeric(24) DEFAULT NULL,
`piece_color` enum('B','R') NOT NULL,
`id` numeric(30) DEFAULT NULL,
`last_action` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
)
How to insert a line ?
position the number 12
piece_color the R
id 0 and 1 . I want to have two numbers here
I did
INSERT INTO `playersrb` VALUES('12','R','01');
The returned error was:
00:20:16 INSERT INTO `playersrb` VALUES('12','R','01') Error Code: 1136. Column count doesn't match value count at row 1 0.00062 sec
Your table name is different than what you are trying to INSERT into.
You also are not inserting the same number of values as there are columns, so you either need to insert a value for each column, or define the columns you want to enter into.
This statement will work to insert a row.
INSERT INTO playersrb VALUES('12','R','01', now());
I am assuming you wanted last_action to default to now(), but to do that you will need to define the columns like this:
INSERT INTO
playersrb
(position, piece_color, id)
VALUES
('12', 'R', '01');
You need to specify the columns to insert if you would like to use VALUES. In your case, it would be something like this:
INSERT INTO `playersrb` (`position`, `piece_color`, `id`) VALUES ('12','R','01');

Creating a table and Inserting values in db browser (sqlite)

I am new at scripting and am trying to create a table and insert values into the table below using DB Browser (SQLite).
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS "Doctor" (
"Doctorid" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
"DoctorName" TEXT NOT NULL,
"DoctorSpecialty" TEXT NOT NULL,
"ConsultationFee" NUMERIC NOT NULL
);
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(2,'Rose','Cardiology',375),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(3,'Johnson','Neurology',250),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(4,'Leath','Pharmacy',400),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(5,'Anderson','Anesthesiology',500),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(6,'Copeland','Radiology',550),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(7,'Macklin','Orthopedic Surgeon',575),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(8,'Witherspoon','Immunizations',100),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(9,'Pope','Billing',50),
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(10,'Cockfield','Pediatrics',100);
COMMIT;
Once I run the script, I receive an error:
Result: near "INSERT": syntax error
At line 7:
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300),
INSERT
Line 7 is: );
Im not sure what im doing wrong, can someone please help. Thanks.
remove Doctorid at insert time because it is AUTOINCREMENT.
INSERT INTO Doctor
(DoctorName,DoctorSpecialty,ConsultationFee) VALUES
('Wells','Respiritory Therapy',300);
and put the semicolon (;) end of the query
Inserting multiple values should be like this. You don't need to repeat INSERT statement.
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300),
(2,'Rose','Cardiology',375),
(3,'Johnson','Neurology',250),
(4,'Leath','Pharmacy',400);
or change the comma to semi colon in each INSERT statement.
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(1,'Wells','Respiritory Therapy',300);
INSERT INTO Doctor
(Doctorid,DoctorName,DoctorSpecialty,ConsultationFee) VALUES
(2,'Rose','Cardiology',375);

Many to many relational database

I have a table where player character information is kept. I have another table where all possible status affects are kept. I am trying to figure out how to create a relationship where any/all/none of the character entries in the first table can be linked to any/all/none of the status entries in the second table. My research has shown me that I will probably need a third table, and may have to use composite Primary Keys and/or surrogate keys?
So here is an update based on responses. I seem to have working what I was hoping to achieve. Here is the code:
create table characters (
char_id int primary key auto_increment,
name varchar(25)
);
create table health_status (
status_id int primary key auto_increment,
stat_name varchar(15)
);
create table char_status (
char_id int,
status_id int,
primary key (char_id, status_id)
);
insert into characters (name) values ('Godzilla');
insert into characters (name) values ('King Kong');
insert into characters (name) values ('Mecha-Dragon');
insert into characters (name) values ('Chris Hanson');
insert into characters (name) values ('Journey');
insert into characters (name) values ('Lou Diamond Phillips');
insert into characters (name) values ('RedHot');
insert into health_status (stat_name) values ('Bleeding');
insert into health_status (stat_name) values ('Shaken');
insert into health_status (stat_name) values ('Frightened');
insert into health_status (stat_name) values ('Petrified');
insert into health_status (stat_name) values ('Poisoned');
insert into health_status (stat_name) values ('Slowed');
insert into health_status (stat_name) values ('Rushed');
insert into health_status (stat_name) values ('Endowed');
insert into char_status (char_id, status_id) values (1, 1);
insert into char_status (char_id, status_id) values (1, 3);
insert into char_status (char_id, status_id) values (1, 6);
insert into char_status (char_id, status_id) values (2, 2);
insert into char_status (char_id, status_id) values (2, 4);
insert into char_status (char_id, status_id) values (3, 7);
insert into char_status (char_id, status_id) values (6, 8);
insert into char_status (char_id, status_id) values (7, 2);
insert into char_status (char_id, status_id) values (7, 7);
select characters.name, health_status.stat_name
from characters
left join char_status on characters.char_id = char_status.char_id
left join health_status ON health_status.status_id =
char_status.status_id;
I have three questions. Does anyone see any way this could be cleaned up, or a better way to achieve my goal? Also, is having the compound PK in the table char_status really doing anything useful? And finally, Is there a way to organize the output with a query to list the character name only once, followed by all its associated status - or is this something for a different language to do? Thanks for everyone's help!
Based on your structure you say you need to further create new table and put data into it.**
In order for you to connect between tableA and TableB you need to have
a Primary key in one and also its reference in other
**. Many to many relationship is something like a mutual one where tableA depends on many elements of tableB and also vice-versa.
You may have to normalize your tables first based on your situation.
Have a look at Normalization_tuorial
Next also have a look at one-many and many-many etc..
As you found in your research
create a third table with 2 fields that will hold the "id" (main field) from those 2 tables you want to make relation many to many...
CREATE TABLE `many_to_many` ( `information_id` INT(11) NOT NULL , `status_id` INT(11) NOT NULL , PRIMARY KEY (`information_id`, `status_id`)) ENGINE = MyISAM;
Pay attension to the PRIMARY KEY that depend on thos 2 fields.
Now you can add for every information_id many status_id relations,
and for status_id many information_id relations.
For first try, run this query to add values to see it
INSERT INTO `many_to_many` (`information_id`, `status_id`) VALUES (1, 1), (1, 2), (2, 1), (2, 2);

MySql auto_increment value incorrect

I found working on the problem.
Using InnoDB
CREATE TABLE UserAccount (
UserID INT NOT NULL AUTO_INCREMENT,
Email CHAR(32) NOT NULL UNIQUE,
Password CHAR(32) NOT NULL,
Status TINYINT DEFAULT 0,
PRIMARY KEY(UserID)
);
Try Insert data.
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test#gmail.com', 3341234, 0);
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test#gmail.com', 3341234, 0);
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test#gmail.com', 3341234, 0);
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test2#gmail.com', 3341234, 0);
The UserID of test#gmail.com is 1 and
the UserID of test2gmail.com is 4, not 2.
I want the result is 2.
What's the solution?
The problem
The default innodb_autoinc_lock_mode is "1". This means InnoDB only locks the auto-increment column on the table until the end of the INSERT statement if the number of rows to be inserted cannot be determined in advance (for example in an INSERT ... SELECT query). For a simple INSERT like your queries, it assigns the auto-increment ID in advance and then allows other inserts to the table immediately, for faster writing.
In general this means the IDs are consecutive but if you use INSERT IGNORE this is a simple insert so the ID will be assigned and then potentially not actually used because the row is a duplicate.
Changing the lock mode
If you absolutely must have a consecutive identifier for each row, you can change the InnoDB auto-increment lock mode by adding the following line to your my.cnf and restarting your MySQL server.
innodb_autoinc_lock_mode = 0
There is more information about this in the manual. Even after this change, there may be gaps in the sequence if the transaction that generates the IDs is rolled back or if the rows are deleted later, but for your example the IDs generated are "1" and "2" as you expected.
Using a trigger to simulate the same effect
If you can't edit your my.cnf or the gaps after roll backs is an issue, you could write a trigger to update the primary key instead. Something like the following works OK. It generates a warning ("Column 'UserID' cannot be null") for each insert but it inserts successfully with consecutive IDs. Unfortunately if you delete the user with the highest ID, the next user will get the same ID again, whereas if you delete a user in the middle of the sequence there will be a gap as with auto-increment.
DROP TABLE UserAccount;
CREATE TABLE UserAccount (
UserID INT NOT NULL,
Email CHAR(32) NOT NULL UNIQUE,
Password CHAR(32) NOT NULL,
Status TINYINT DEFAULT 0,
PRIMARY KEY(UserID)
);
CREATE TRIGGER UserAccount_before_insert BEFORE INSERT ON UserAccount
FOR EACH ROW SET NEW.UserId = (
SELECT COALESCE(MAX(UserId), 0) + 1 FROM UserAccount);
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test#gmail.com', 3341234, 0);
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test#gmail.com', 3341234, 0);
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test#gmail.com', 3341234, 0);
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test2#gmail.com', 3341234, 0);
I'd have to add, I'm not completely sure how this trigger would perform if you made lots of inserts concurrently from more than one connection. So if that's an issue you might need to do some more research.
In your insert query use IGNORE, means its not insert duplicate record.
every time when you insert same UserID AUTO_INCREMENT count increase and then different UserID come in, it insert incremented auto_increment's value (like 4 in your case)
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test#gmail.com, 3341234, 0); -- auto_increment = 1
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test#gmail.com, 3341234, 0); -- auto_increment = 2
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test#gmail.com, 3341234, 0); -- auto_increment = 3
INSERT IGNORE INTO UserAccount VALUES (NULL, 'test2#gmail.com, 3341234, 0); -- auto_increment = 4
Link

How can I insert data without specifying a value for a non auto-increment primary key?

I have this table:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
1. insert into persons values (1, 'John', 'Smith', 'LA', 'LA');
2. insert into persons (p_id, lastname, firstname, address, city) values (2, 'John', 'Smith', 'LV', 'LV');
How can I insert data into a table, without specifying a value for a primary key (the primary key doesn't have the "auto_increment" attribute).
I tried with:
insert into persons values ('John', 'Smith', 'LA', 'LA');
insert into persons values (null, 'John', 'Smith', 'LA', 'LA');
insert into persons values (auto, 'John', 'Smith', 'LA', 'LA');
but no luck
Primary keys cannot be null, and if you don't set them to auto increment, then how does MySQL know what you want to put in the table? You need to either specify the ID (perhaps by selecting the MAX(P_Id) and adding 1 to it) or set it to auto increment.
Although simply adding an auto increment field is definitely the best approach, you could try something like this:
INSERT INTO Persons (P_Id, FirstName, LastName, Address, City)
VALUES ((SELECT MAX(P_Id) + 1 FROM Persons), 'John', 'Smith', 'LA', 'LA');
This uses a subselect, so if you're using an old version of MySQL it may not work.
I have seen this implemented as
DEFAULT value on the PK column (say -9999)
A table that holds the Current_PK value
An INSERT trigger that changes that PK from -9999 to Current_PK and increments Current_PK
Another way that I have seen is to get the MAX from the table and increment it and put it into the new row.
I must say, that both these methods caused bad data, caused locking and blocking and degraded performance.
In your case, I do not see a way other than actually specifying a value for PK.
Select p_id+1 From Person OrderBy p_id desc limit 1;
When loading a row into a table with auto-increment you can specify a value provided that value is NOT less than the highest value in that key. This works the same as a UNIQUE key and will error as if it is a duplicate. Otherwise it will treat the new loaded value as the new highest value for that key.
I am most curious to know why anyone would want to use a primary key without using auto-increment. The auto-increment makes for a most elegant way of avoiding duplicate data in any table. If the rest of the data is identical with another row in that table it can be identified and fixed/deleted. Used in combination with another row which is a unique key (to catch any duplicates) the table becomes very robust.
ianm