I have a lot of existing records which I want to copy using an INSERT, for example if I have a query:
SELECT * FROM `threats` WHERE biDataset=9;
The common key is biDataset, the primary key in this table is biPK which is auto incremented on each insert. Here is the table structure:
CREATE TABLE `threats` ( `biPK` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Primary key', `biDataset` BIGINT(20) UNSIGNED NOT NULL COMMENT 'ID of dataset', `jsonParams` LONGTEXT NOT NULL COMMENT 'JSON object containing all parameters' COLLATE 'utf8mb4_bin', `txtTrainee` MEDIUMTEXT NULL DEFAULT NULL COMMENT 'Trainee host name (NULL if not applicable)' COLLATE 'utf8mb4_unicode_ci', PRIMARY KEY (`biPK`) USING BTREE, UNIQUE INDEX `dataset and json` (`biDataset`, `jsonParams`) USING HASH, INDEX `datasetIdx` (`biDataset`) USING BTREE, INDEX `jsonIdx` (`jsonParams`(768)) USING BTREE ) COMMENT='Table of datasets' COLLATE='utf8mb4_unicode_ci' ENGINE=InnoDB AUTO_INCREMENT=174;
What I want to do is copy all the records that exist where biDataset is 9, creating new records, I need to be able to specify the new biDataset too, 15 to use for all copies instead of 9.
I’ve tried:
INSERT INTO `threats` (biDataset, txtTrainee, jsonParams) SELECT 15, NULL, jsonParams FROM `threats` WHERE biDataset=9;
This results in:
SQL Error (1364): Field 'DB_ROW_HASH_1' doesn't have a default value
Advertisement
Answer
The solution was to modify the table structure to:
CREATE TABLE `threats` ( `biPK` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Primary key', `biDataset` BIGINT(20) UNSIGNED NULL DEFAULT NULL COMMENT 'ID of dataset', `jsonParams` LONGTEXT NULL DEFAULT NULL COMMENT 'JSON object containing all parameters' COLLATE 'utf8mb4_bin', `txtTrainee` MEDIUMTEXT NULL DEFAULT NULL COMMENT 'Trainee host name (NULL if not applicable)' COLLATE 'utf8mb4_unicode_ci', PRIMARY KEY (`biPK`) USING BTREE, UNIQUE INDEX `dataset and json` (`biDataset`, `jsonParams`) USING HASH, INDEX `datasetIdx` (`biDataset`) USING BTREE, INDEX `jsonIdx` (`jsonParams`(768)) USING BTREE ) COMMENT='Table of datasets' COLLATE='utf8mb4_unicode_ci' ENGINE=InnoDB AUTO_INCREMENT=174 ;