Insert a line with different values - mysql

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');

Related

SQL Insert with AUTO INCREMENT

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' );

JSON equivalent of INSERT...ON DUPLICATE KEY UPDATE, and increase current value on existent

I have a situation like this, simplified:
CREATE TABLE `user_points` (
`date` date NOT NULL,
`user_id` mediumint(8) unsigned NOT NULL,
`points` int(11) NOT NULL,
PRIMARY KEY (`date`, `user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
so, if today a user earns a point, I make:
INSERT INTO user_points (date, user_id, points) VALUES (CURDATE(),?,1)
ON DUPLICATE KEY UPDATE points=points+1;
Now, imagine I want to store these points into a JSON field, that contains not only points but it may contain other properties (these properties are dynamic, some clients will never use any, other will use a lot of them, that's why I like JSON)
So, instead of adding to points, I want to set $.points on a data column.
Is it possible to make a single query that does this?
If there is no row with such date and user_id, insert a new row with data={"points": 1}
If there is a row and data is null, SET data="{"points": 1}"
If there is a row with some json, but not $.data, JSON_SET(data, '$.points', 1)
if there is a row and some $.points, increase the points by one.
I tried:
SELECT JSON_SET('{"a": 1, "l": 2}', '$.points',
JSON_EXTRACT('{"a": 1, "l": 2}', '$.points')+1) AS 'Data';
but it doesn't work (because NULL + 1 = NULL instead of 1)
EDIT: that can be solved with COALESCE, but I'm not sure it's the best solution:
SELECT JSON_SET('{"a": 1, "l": 2}', '$.points',
COALESCE(JSON_EXTRACT('{"a": 1, "l": 2}', '$.points'), 0)+1) AS 'Data';
the full query would be:
INSERT INTO user_points (date, user_id, data) VALUES (CURDATE(),?,'{"points":1}')
ON DUPLICATE KEY UPDATE data=JSON_SET(data, '$.points',
COALESCE(JSON_EXTRACT(data, '$.points'), 0)+1);
This is the working solution I found so far, it needs COALESCE twice (in case data is null, and in case data.points is null:
INSERT INTO user_data (date, user_id, data) VALUES (CURDATE(), ?, '{"points":1}')
ON DUPLICATE KEY UPDATE data=JSON_SET(COALESCE(data, '{}'), '$.points',
COALESCE(JSON_EXTRACT(data, '$.points'), 0)+1);
I wonder why it adds a .0..

I unable to Insert a value from a char that has been CAST as Integer and added by 1

I convert an id which is in a char column datatype. after that, I want to add it by 1 (plus 1).
Could you help me? why my query is not working?
query:
INSERT INTO `countries` (`id`, `country_name`) VALUES ((SELECT MAX(CAST(`id` as INTEGER)) AS `max_id` FROM `countries`) + 1, 'India');
The following would run:
INSERT INTO `countries` (`id`, `country_name`)
SELECT MAX(CAST(`id` as INTEGER)) + 1, 'India'
FROM `countries`;
But I think it would be easier if you just make the id column an AUTO_INCREMENT.
This is not how you should be doing identifiers.
If you want incrementing id values, you want to use the AUTO_INCREMENT feature when creating your table.
Your way is dangerous, there's always a possibility of two transactions running at the same time picking the same "next ID".
Just create a table with the flag on:
CREATE TABLE countries (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO countries (`name`) VALUES ('India');

Generate unique and random code digit with MySQL

Initial goal:
I would like to generate random and unique codes (6 digits) in a table.
I use a SQL query like this one to do that:
SELECT SUBSTRING(CRC32(RAND()), 1, 6) as myCode
FROM `codes`
HAVING myCode NOT IN (SELECT code FROM `codes`)
I asked me about how it will react when there will be no more available codes so I do the following test
Test context:
MySQL version: 5.5.20
MySQL Table:
CREATE TABLE `codes` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`code` VARCHAR( 10 ) NOT NULL ,
UNIQUE (
`code`
)
) ENGINE = InnoDB;
Initial data:
INSERT INTO `codes` (`id`, `code`)
VALUES (NULL, '1'), (NULL, '2'), (NULL, '3'), (NULL, '4'), (NULL, '5'), (NULL, '6'), (NULL, '7'), (NULL, '8');
SQL Query:
SELECT SUBSTRING(CRC32(RAND()), 1, 1) as myCode
FROM `codes`
HAVING myCode NOT IN (SELECT code FROM `codes`)
By execute this query, I expect that it will always return 9 because it is the only code of one digit which does not exists.
But the result is:
Sometime it return any rows
Sometime it return rows with values that already exists
I don't understand this behavior so if someone can help :)
So the big question is:
How MySQL can return rows with values that already exists?
Thanks
I would fill a sequencetable table with all the possible values, in sequence.
Then the random query just randomly selects records from the sequencetable, and each time it picks a record it deletes it. This way you will surely get all the numbers, without wasting time in finding a "hole" number (not already picked up).
CREATE TABLE `sequencetable`
(
`sequence` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`sequence`)
)
ENGINE=InnoDB
AUTO_INCREMENT=1;
Fill the sequence (no need for the AUTOINCREMENT actually).
DECLARE i INT;
SET i=1;
REPEAT
INSERT INTO sequencetable VALUES (i);
SET i=i+1;
UNTIL i>999999 END REPEAT;
Select a random record from the sequence (do this in a loop until records are available):
DECLARE sequencen INT;
SET sequencen =
(SELECT sequence FROM sequencetable ORDER BY RAND() LIMIT 1);
DELETE FROM sequencetable WHERE sequence = sequencen;

INSERT statement for MySQL table

CREATE TABLE IF NOT EXISTS `MyTable` (
`ID` SMALLINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO MyTable (ID,Name) VALUES (ID=4,Name='xxx')
or
INSERT INTO MyTable (Name) VALUES (Name='xxx')
The problem is that both INSERT statements produce the entry (4,0). Why 0 instead of "xxx"?
UPDATE: Primary key changed.
This should do the job :
INSERT INTO MyTable (ID, Name) VALUES (4, 'xxx')
I'm pretty sure it would be something like this, instead...
INSERT INTO MyTable (Name) VALUES ('xxx')
No need for the Name= part, since you've already specified which column you wish to insert into with the first (Name) definition.
Because the expression Name='xxx' is false, hence evaluates as zero.
You use the column=expression method use in on duplicate key update clauses as described here, not in the "regular" section of inserts. An example of that:
insert into mytable (col1,col2) values (1,2)
on duplicate key update col1 = col1 + 1
You should be using the syntax:
INSERT INTO MyTable (ID,Name) VALUES (4,'xxx')
Is that syntax of Name='xxx' valid? Never seen it before, i assume it is seeing it as an unquoted literal, trying to convert it to a number and coming up with 0? I'm not sure at all
Try this:
INSERT INTO MyTable (Name) VALUES ('xxx')
This is because you should mention the name of the column in the values part. And also because you do not define you primary key correctly (airlineID is not part of the field list)
CREATE TABLE IF NOT EXISTS `MyTable` (
`ID` SMALLINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO MyTable (ID,Name) VALUES (4,'xxx')
INSERT INTO MyTable (Name) VALUES ('xxx')
Try this
INSERT INTO MyTable (ID,Name) VALUES (4,xxx)
For more Info just visit this link