简体   繁体   中英

MySQL Insert multiple rows

I have a setting table and am trying to insert data settings for a user.

Table:

id (userid)|keyword|data|flags (setting id)
33         |name   |John|22
33         |sex    |male|21
33         |userid |33  |1

I am trying to Insert using this method:

INSERT INTO users_settings
  (id,keyword, data, flags)
VALUES
 ( '33','name', 'John', '22'),
 ( '33','sex', 'male', '21'),
 ( '33','userid', '33', '1'),

But I am getting a MySQL error:

#1062 - Duplicate entry '33-name' for key 'PRIMARY'

the id is not auto inserted (since it's used to hold userid).

my table schema:

CREATE TABLE IF NOT EXISTS `user_settings` (
  `id` varchar(20) NOT NULL DEFAULT '-1',
  `keyword` varchar(30) NOT NULL DEFAULT '',
  `data` varchar(255) NOT NULL,
  `flags` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`,`keyword`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Since the column flags is int

INSERT INTO users_settings
  (id,keyword, data, flags)
VALUES
 ( '31','name', 'John', 22),
 ( '32','sex', 'male', 21),
 ( '33','userid', '33', 1)

Ok, I think TWO problems here;

1) your ID (used id ) field might be Primary Key.

2) You are trying to insert CHAR in INT filed of flag.

So please Try;

INSERT INTO user_settings
  (id,keyword, data, flags)
VALUES
  ( '31','name', 'John', 22),
  ( '32','sex', 'male', 21),
  ( '33','userid', '33', 1);

EDIT:

check this SQL it works perfectly,

only one thing, create table has name user_settings and you insert have table name users_settings . Otherwise it worked perfectly...!!

I think there is no problem in inserting of your data.

You have made the candidate key by taking combination of two fields as primary key.

when we define more than 1 key then combination of primary keys are always said to be the candidate key , In this case you can't insert the record which is having both the values same as inserted before.

After alanysing your answer i can say that you must have inserted the same record before.

this one -> id = 33 -> keyword = name

So ,try another and different combination of values , im very sure you will not get any error while inserting.

What worked for me was this format, and for some reason i had to order them by FLAGS (1-22)

INSERT INTO users_settings
  (id,keyword, data, flags)
VALUES
 ( '33','userid', '33', '1'),
 ( '32','sex', 'male', '21'),
 ( '31','name', 'John', '22')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM