MySql multiple columns as primary key doesn't work - mysql

I create the MySql table by the following sql statement:
CREATE TABLE IF NOT EXISTS `mytable` (
`agent` varchar(64) NOT NULL,
`name` varchar(40) NOT NULL,
`app` varchar(64) NOT NULL,
PRIMARY KEY (`app`,`agent`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
As you see, the field 'app' and 'agent' is the primary key. But unfortunately it doesn't work when I insert the following data, it always show the duplicated key in 'app' field:
app agent name
-------------------------
MyApp ios cde
MyApp android abc
Can anybody tell me anything wrong? Thanks

In your primary key app and agent are a primary key together, not two individual keys.
You'll be able to add many rows with app = 'MyApp' as long as agent differs. And the other way around.
If you wan't to disallow multiple rows with the same app and multiple rows with the same agent add normal unique indexes.
CREATE TABLE IF NOT EXISTS `mytable` (
`agent` varchar(64) NOT NULL,
`name` varchar(40) NOT NULL,
`app` varchar(64) NOT NULL,
UNIQUE app_index (`app`),
UNIQUE agent_index (`agent`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The set of primary keys in MySQL does not check for individual unique values, it will give duplicate error when you will try to insert same set of values in multiple records, but both the columns will not accept NULL values
Eg.
app agent name
-------------------------
MyApp ios cde
MyApp ios abc - it will give you error as "Duplicate entry 'MyApp-ios' for key 'PRIMARY'"
may this will help you

Related

The duplicate key value is (<NULL>, <NULL>)

So I'm trying to migrate a table from MySQL to MSSQL (sql server migration assistant MySQL), but I get this error:
Migrating data...
Analyzing metadata...
Preparing table testreportingdebug.testcase...
Preparing data migration package...
Starting data migration Engine
Starting data migration...
The data migration engine is migrating table '`testreportingdebug`.`testcase`': > [SwMetrics].[testreportingdebug].[testcase], 8855 rows total
Violation of UNIQUE KEY constraint 'testcase$Unique'. Cannot insert duplicate key in object 'testreportingdebug.testcase'. The duplicate key value is (<NULL>, <NULL>).
Errors: Violation of UNIQUE KEY constraint 'testcase$Unique'. Cannot insert duplicate key in object 'testreportingdebug.testcase'. The duplicate key value is (<NULL>, <NULL>).
Completing migration of table `testreportingdebug`.`testcase`...
Migration complete for table '`testreportingdebug`.`testcase`': > [SwMetrics].[testreportingdebug].[testcase], 0 rows migrated (Elapsed Time = 00:00:00:01:352).
Data migration operation has finished.
0 table(s) successfully migrated.
0 table(s) partially migrated.
1 table(s) failed to migrate.
I've just copied three rows from my table, and this is what they look like:
'1', 'Pump# TimeToService', NULL, NULL, 'A general test case comment ...', '0'
'2', 'Config.SlaveMinimumReplyDelay', NULL, NULL, NULL, '0'
'3', 'Config.RESERVED', NULL, NULL, NULL, '0'
If you are wondering how the colons in the MySQL table is setup, here you go:
Is is because right, left and comment can be null?
DDL of table
CREATE TABLE `testcase` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`TestCaseName` varchar(150) DEFAULT NULL,
`Left` int(11) DEFAULT NULL,
`Right` int(11) DEFAULT NULL,
`Comment` text,
`Hidden` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `Unique` (`Left`,`Right`)
) ENGINE=InnoDB AUTO_INCREMENT=10580 DEFAULT CHARSET=utf8
Had to remove the Unique part, since their are only NULL.
ALTER TABLE `testreportingdebug`.`testcase`
DROP INDEX `Unique`;
If you want the strict equivalent in SQL Server of your MySQL table you must create it like this :
CREATE TABLE testcase (
id int NOT NULL IDENTITY PRIMARY KEY,
TestCaseName varchar(150),
[Left] int,
[Right] int,
Comment VARCHAR(max),
[Hidden] tinyint DEFAULT 0,
);
CREATE UNIQUE INDEX X_testcase_right_left
ON testcase ([Left], [Right])
WHERE [Left] IS NOT NULL
AND [Right] IS NOT NULL;
By the way, column names "Right", "left", "hidden" are SQL / MS SQL Server reserved words and should not be used at anytime for SQL identifiers (table name, colum name, proc name...)
The complete list can be obtain here

Field 'category_id' doesn't have a default value MySQL

I'm learning SQL.
I'm trying to insert data. My MySQL database looks like this.
CREATE TABLE category (
category_id CHAR(100),
category_name VARCHAR(120) NOT NULL,
PRIMARY KEY (category_id)
)
I ran this command
INSERT INTO category (category_name) VALUES ("test");
But I got this error
ERROR 1364 (HY000): Field 'category_id' doesn't have a default value
Thank you in advance.
If you want to have an incrementing ID it would need to be an int. You Generally want to make ID's integers not chars to speed up lookup regardless.
CREATE TABLE IF NOT EXISTS category (
`category_id` INT NOT NULL AUTO_INCREMENT,
`category_name` VARCHAR(120) NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET = utf8mb4 COLLATE utf8mb4_unicode_ci;
That will let you insert without adding your own ID, and automatically generate unique ID's for the records.
Issue was you set your category_id field to not have a default value and also not allow null, which means you -have- to set a value for it in the insert. If you wanted to use your existing table you would need to do this:
INSERT INTO category (category_id, category_name) VALUES ("someid", "test");

Creating a table with two different sorted columns

I have created the simple table in a MySQL database;
CREATE TABLE `opportunity` (
`customer` varchar(255) NOT NULL DEFAULT '',
`category` varchar(255) NOT NULL DEFAULT '',
`bill_amount` decimal(13,2) NOT NULL,
PRIMARY KEY (`bill_amount`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I used 'bill_amount' as my primary key so I could remove duplicate information when I import data to the table, but I need to also need to separate records by separate categories as well. Here is an example of what I have, what results I am getting, and what I need. If anyone could give me advice on how to properly set up my table so it groups the data as need I would appreciate the help.

Resolving a duplicate primary key on mysql import

I'm looking to append a comments table from one WordPress site to another. The users are different. When I import the comments from site B to A, I run into a duplicate key issue; comment_id is already taken.
So how can I resolve this and append the table with a simple .sql file? Would I have to take the user information, generate a new user, check for comments made on site B, pull the content and postID, then go back to site A and recreate the comment for the newly created user!?
What a headache! THanks.
if your only problem is a duplicate key issue, go to the end of your sql file after
ENGINE=MyISAM
and make it
ENGINE=MyISAM AutoIncrement=a nubmer above the last id in the new database
or
Query database A for the last id then add one and use it on a new insert query.
Example 1:
CREATE TABLE IF NOT EXISTS `movies` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`year` int(4) NOT NULL,
`size` varchar(255) NOT NULL,
`added` date NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `title` (`title`,`year`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
The Inserts From My Dump:
INSERT INTO `movies` (`title`, `year`, `size`, `added`) VALUES
('[REC] 2', 0, '716688', '2011-09-23'),
('5 Days of War', 0, '1435406', '2012-01-09'),
('[REC]', 0, '1353420800', '2011-11-06');
See how i didnt include the PRIMARY KEY (id) in my includes, but it will still check against my UNIQUE KEY and see if the title exists. Just a little demo that hopefully helps out. If your table already exists on the new database then just skip to the inserts and dont include the primary key and it will be auto set on a new insert to the next available value.

MySQL Duplicate primary key on unexisting key

I've got a weird problem on a MySQL table. When trying to insert a new row, it says the primary key is duplicate. My primary key is auto incremental and is not set within my query (automatically set by MySQL).
The problem is I get a "Duplicate primary key" error on a key that doesn't even exists (I checked). I solved the problem increasing the current auto_increment value but I can't understand how it happened.
Any help would be great.
Edit
Table creation
CREATE TABLE `articles_mvt` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`ext_article_id` int(5) NOT NULL,
`date_mvt` date NOT NULL,
`qte` float(4,2) NOT NULL,
`in_out` enum('in','out') NOT NULL,
`ext_nateco_id` int(5) NOT NULL,
`ext_agent_id` int(5) NOT NULL COMMENT 'Demandeur',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1647 ;
Problematic query
INSERT INTO articles_mvt (
`ext_article_id`,
`date_mvt`,
`qte`,
`in_out`,
`ext_nateco_id`,
`ext_agent_id`
)
VALUES (
'".$_POST["numArticle"]."',
'".dateSql($_POST["date_mvt"])."',
".$_POST["qte_entier"].".".$_POST["qte_virgule"].",
'".$_POST["in_out"]."',
".$_POST["numNateco"].",
".$_POST["demandeur"]."
)
FYI variables are sanitized earlier in the code ;)
Well i think at that time you did not check auto Inc flag on primary key. So when you try to enter than value 0 is insert in the primary key and for second entry it gives error. like that
ID Value
0 A ok it not give error
0 ff it gives error..
Or you may try to insert a row whose ID is already exist like
ID Value
11 A ok it not give error
11 ff it gives error..