I have a query like
INSERT INTO support_users VALUES("1",,"2","1","4",,,"2017-05-06 20:24:36");
but new MySQL not inserting given error Error Code: 1064
but I changed it to
INSERT INTO support_users VALUES("1","","2","1","4",,,"2017-05-06 20:24:36");
working
but previous MySQL not having such an issue.how to solve that. without changing query
table definition
CREATE TABLE support_users (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`client` int(11) DEFAULT NULL,
`user` int(11) DEFAULT NULL,
`ticket` int(11) DEFAULT NULL,
`scope` int(11) DEFAULT NULL,
`notify` tinyint(1) DEFAULT NULL,
`email` tinyint(1) DEFAULT NULL,
`added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8;
Firstly, respect the Datatype. If its Integer don't use quotes.
The right way to approach your problem will be use of NULL. So this works across any version of MySQL.
INSERT INTO support_users VALUES(1,NULL,2,1,4,NULL,NULL,'2017-05-06 20:24:36');
1)
Integer column values should not be quoted.
So "1" becomes 1
2)
Auto Increment values should not be manally given to the SQL -- let it work it out itself.
3)
Inserting NULL using the NULL keyword.
4)
Your date-time column is set in its definition to show the current date-time of the row being inserted when it is inserted. As you are inserting (rather than updating, etc.) you therefore do not need to include this data.
5)
It is easier for your sanity to also list which columns are being added to with the INSERT instruction.
6)
Use single quotes ' around string data not double quotes ("), when working directly with MySQL.
Result:
INSERT INTO support_users( `id`, `ticket`, `scope` , `notify`)
VALUES (1, 2,1,4);
This will cause errors if you try to insert twice, because you are forcing the Primary Key (id) to be 1. To avoid this, skip the Auto Increment (id) column value.
Or for clarity only; the full SQL:
INSERT INTO support_users VALUES (1, NULL, 2, 1, 4, NULL, NULL, '2017-05-06 20:24:36');
Skipping the Auto Increment (id) column value (as referenced above):
INSERT INTO support_users VALUES (NULL, NULL, 2, 1, 4, NULL, NULL, '2017-05-06 20:24:36');
Related
I'm using MySQL Workbench.
I would like to create a table named courseInfo and I want to put a column named moduleCode in it, but I want it to always be similar in format: CFSM H0000 where the four zeros are a number that increases starting with 0000.
For example:
CFSM H0001
CFSM H0002
[..]
You cannot auto-increment character type columns in MySQL, as auto-increment is only possible on integer type columns. One (alphanumeric) auto-incrementing moduleCode column would therefore not be possible. However, you could try splitting up the moduleCode into two columns, for example like so:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
KEY (`id`)
) AUTO_INCREMENT = 0;
Where prefix could for example be "CFSM H" and id could be 0001
Then, upon executing SELECT statements, you could merge the prefix column with the id column into a moduleCode column with CONCAT, e.g.:
SELECT CONCAT(`prefix`, `id`) as `moduleCode` FROM `courseInfo`;
An alternative approach (from MySQL version 5.7 and up) seems to be the use of a generated column, for example:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`moduleCode` CHAR(10) AS (CONCAT(`prefix`, `id`)),
KEY (`id`)
) AUTO_INCREMENT = 0;
However, the above example of a generated column would not work, because moduleCode is dependent on an auto-increment column, and the auto-increment is not executed yet at the time the generated column is computed. See also: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html. It would throw an ER_GENERATED_COLUMN_REF_AUTO_INC error.
You could therefore use the first solution, or try to add moduleCode as a column and use an AFTER INSERT trigger to update its value:
CREATE TABLE `courseInfo` (
`prefix` CHAR(6) NOT NULL DEFAULT 'CFSM H',
`id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT,
`moduleCode` CHAR(10),
KEY (`id`),
UNIQUE KEY `unique_index` (`prefix`,`id`)
) AUTO_INCREMENT = 0;
DELIMITER //
CREATE TRIGGER `addModuleCode` AFTER INSERT ON `courseInfo`
FOR EACH ROW
BEGIN
UPDATE `courseInfo` SET `moduleCode` = CONCAT(NEW.`prefix`, NEW.`id`) WHERE `prefix` = NEW.`prefix` AND `id` = NEW.`id`;
END;//
DELIMITER ;
I am using the INSERT function to try and add new values to a table. While there is no error when I run the query, it is not showing the new attributes added to the table. I have no idea why. I also have safe updates turned off. The values entered also match the value type for each column of the table.
CODE ENTERED:
INSERT INTO productlines
VALUES
('Jet Packs', 'Futuristic flying machines that only exist in prototype.', NULL, NULL),
('Jet Skis', 'Much more realistic things that very much exist already.', NULL, NULL),
('Wheelbarrows', 'I cannot believe we actually stock these.', NULL, NULL);
SELECT *
FROM productlines;
CREATE TABLE `productlines` (
`productLine` varchar(50) NOT NULL,
`textDescription` varchar(4000) DEFAULT NULL,
`htmlDescription` mediumtext,
`image` mediumblob,
PRIMARY KEY (`productLine`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
INSERT INTO
[name of your **TABLE**](col1, col2, col3)#NAME OF YOUR COLUMNS
VALUES
('value for col1','value for col2','value for col3'),
You didn't add the column names for which you are performing the insert
Here's my table:
CREATE TABLE `files` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`filename` varchar(255) NOT NULL,
`hash` varchar(255) NOT NULL,
`path` varchar(255) NOT NULL,
`mimetype` varchar(255) NOT NULL,
`size` int(10) unsigned NOT NULL,
`uploaded` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `filename` (`filename`,`hash`)
)
Let's say I insert something with filename "myFile" and hash "abc". Let's say it's not a duplicate and its id is 45.
Then let's say I insert some more queries so that the auto_increment index is higher now. For the sake of this example we'll say it's 70.
Now what happens when I do this:
insert into files(filename, hash, ...) values ("myFile", "abc", ...) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
What actually happens? Will it update the id of the file I am currently inserting to be 45? Or will it change the ID of the existing row to be 70? In the case of the former does that mean the old row is written over? In the case of the latter how does it know to use 45?
If neither (filename, hash) does not match, the IODKU statement will act like
insert into files(filename, hash, ...) values ("myFile", "abc", ...)`
And your subsequent SELECT last_insert_id will get the new id.
Else it will do a mostly no-op UPDATE. Your SET contains only id=LAST_INSERT_ID(id), which does not change id. However, it does capture the existing value of id (45) so that your subsequent SELECT last_insert_id will get that value.
So, either way, you get the id of the row, whether it was INSERTed or UPDATEd.
(Yeah, the syntax is kinda kludgy.)
I have a table in which there is a column name with SP varchar(10) NOT NULL. I want that column always to be unique so i created unique index on that column . My table schema as follows :
CREATE TABLE IF NOT EXISTS `tblspmaster` (
`CSN` bigint(20) NOT NULL AUTO_INCREMENT,
`SP` varchar(10) NOT NULL,
`FileImportedDate` date NOT NULL,
`AMZFileName` varchar(50) NOT NULL,
`CasperBatch` varchar(50) NOT NULL,
`BatchProcessedDate` date NOT NULL,
`ExpiryDate` date NOT NULL,
`Region` varchar(50) NOT NULL,
`FCCity` varchar(50) NOT NULL,
`VendorID` int(11) NOT NULL,
`LocationID` int(11) NOT NULL,
PRIMARY KEY (`CSN`),
UNIQUE KEY `SP` (`SP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10000000000 ;
Now i want that if anybody tries to insert duplicate record then that record should be inserted into a secondary table name tblDuplicate.
I have gone through this question MySQL - ignore insert error: duplicate entry but i am not sure that instead of
INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200;
can i insert duplicate row into another table ?
what changes needed to be done in main table scheme or index column ?
**Note : Data will be inserted by importing excel or csv files and excel files generally contains 500k to 800 k records but there will be only one single column **
I believe you want to use a trigger for this. Here is the MySQL reference chapter on triggers.
Use a before insert trigger. In the trigger, check if the row is a duplicate (maybe count(*) where key column value = value to be inserted). If the row is a duplicate, perform an insert into your secondary table.
I am trying to add X to some table in my DB, but I am getting this error. Even if X doesn't exist in the table, it say it's there. Although X is added to the DB, I want to get rid of this error. I don't know if it's relevant at all, but I'm using Mysqli's prepared statements and this error is printed using $statement->errno." ".$statement->error. Could someone explain this to me? Thanks.
UPDATE: this is the code: X = USER_USERNAME
$stmt = $mysqli->prepare("INSERT INTO USERS (USER_USERNAME, USER_EMAIL, USER_BIRTHDAY, USER_PASSWORD, USER_SALT, USER_IP, USER_ACTIVATION_CODE) VALUES (?,?,?,?,?,INET_ATON(?),?)");
$stmt->bind_param('sssssss',$username,$email,$date,$hashed_password,$salt,$IP,$activation_code);
$stmt->execute();
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
else {
echo "ok";
}
SHOW CREATE TABLE USERS:
CREATE TABLE `USERS` (
`USER_ID` int(11) NOT NULL AUTO_INCREMENT,
`USER_FIRSTNAME` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
`USER_LASTNAME` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
`USER_USERNAME` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
`USER_PASSWORD` varchar(128) CHARACTER SET utf8 DEFAULT NULL,
`LEVEL_ID` int(11) NOT NULL,
`USER_BIRTHDAY` date DEFAULT NULL,
`USER_EMAIL` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
`USER_GENDER` enum('M','W','U') CHARACTER SET utf8 DEFAULT NULL,
`USER_COUNTRY` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
`USER_LOCATION` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
`USER_ADDRESS` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`USER_HOUSENUMBER` varchar(8) CHARACTER SET utf8 DEFAULT NULL,
`USER_AVATAR` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`USER_REGISTRATION_DATE` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`USER_ACTIVATION_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`USER_STATUS` enum('REGISTERED','ACTIVE','BANNED','NONACTIVE') CHARACTER SET utf8 DEFAULT NULL,
`USER_BANNED_DATE` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`USER_LATEST_LOGIN` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`USER_EXP` bigint(20) DEFAULT NULL,
`USER_DESCRIPTION` text CHARACTER SET utf8,
`USER_ACTIVATION_CODE` varchar(32) CHARACTER SET utf8 NOT NULL DEFAULT '0',
`USER_SALT` varchar(15) CHARACTER SET utf8 NOT NULL,
`USER_IP` int(10) NOT NULL,
`USER_REMEMBER_KEY` varchar(32) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`USER_ID`),
UNIQUE KEY `USER_USERNAME` (`USER_USERNAME`),
UNIQUE KEY `USER_EMAIL` (`USER_EMAIL`),
KEY `LEVEL_ID` (`LEVEL_ID`)
) ENGINE=MyISAM AUTO_INCREMENT=30 DEFAULT CHARSET=latin1
that's because you are trying to insert or update a value violating a constraint (like PK or UK), for example
if your Table have ID an it's a PK or a Unique Key, you can only have ONE UNIQUE VALUE... it's not possible no repeated....
with a Unique Key you can have Null... but never repeat values in the same column, because you will be breaking the constraint... for more information take a look to http://dev.mysql.com/doc/refman/5.0/es/constraints.html
You already defined a Primary or Unique Key, but again you tried to insert the same value. That time since already there exists a same value, it is not possible to have a redundant value for the primary key or unique key.
It is something like this. Consider you have a table with id and name, with id as primary key. You insert first row as:
INSERT INTO `users` (`id`, `name`) VALUES (1, 'Praveen');
INSERT INTO `users` (`id`, `name`) VALUES (1, 'Kumar');
The second query violates the id uniqueness.
Solution: Try to truncate the table and then run the query again, if it is possible.
Some steps to try
Check for other fields with unique constraints being violated too.
See what query is getting generated.
Put the same query in phpMyAdmin and check.
If you are getting that error then X does exist in the table. Apparently you have not noticed it, but it's there. (Check for things like trimmed spaces, and case sensitivity.)
If you don't get the error in phpMyAdmin then the query you think you are sending is not actually the query you are sending. Most likely you are sending blank for the field, and after you do it once, all further query are using the identical blank value.
Easiest way to check is delete everything from the table (copy it elsewhere first if you want). Then run the query and see what actually got inserted vs. what you expected to get inserted.
You are probably trying to insert a record with the ID (or some other field) 1 set, while such a record already exists in the table. The field that is the primary key must have a unique value for each record.
You could try a simple error check to avoid this error:
$rows = mysql_query("SELECT X from tablenme WHERE X = Y;");
if(mysql_num_rows($rows) > 0){
echo 'Error Messege';
}else{
insert...
}
where X is the primary key or foregin key column and Y is the value to be inserted in that column.
EDIT: Some of the problems that might have caused the problem may be that you have not specified certain columns that can't be null in you insert statement.
Like LEVEL_ID and USER_REMEMBER_KEY. They are set to NOT NULL but the values are not being inserted using the insert statement.
I also don't understand why you are inserting 'sssssss' when the first column is USER_USERNAME and its corresponding value is $username. Do check that too.
SQL Fiddle