Multiple primary key defined ошибка

Facing an error in MySQL Database Server as specified in the title of this article, “Multiple primary key defined” will […]

Facing an error in MySQL Database Server as specified in the title of this article, “Multiple primary key defined” will be discussed in this article itself. This is the actual execution of the SQL Command performed in a MySQL Command Console :

mysql> alter table user_role add id int auto_increment primary key;
ERROR 1068 (42000): Multiple primary key defined

The table named ‘user_role’ can be described as follows :

mysql> desc user_role;
+---------+---------+------+-----+---------+-------+
| Field   | Type    | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| id_user | int(11) | NO   | PRI | NULL    |       |
| id_role | int(11) | NO   | PRI | NULL    |       |
+---------+---------+------+-----+---------+-------+
2 rows in set (0,01 sec)

The table above has already a primary key on it. The primary key itself is a composite primary key which consists of two columns. In this context,  adding another primary key is not allowed. So, in order to add another primary key, it means the table must be altered or to make it more easier, just drop the table and recreate it with just one primary key with the rest of the column is defined as a normal field without the attribute of primary key. To prove it the column has a composite primary key, just execute the following command :

mysql> show create table test;
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                 |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------+
| test  | CREATE TABLE `test` (
  `id_user` int(11) NOT NULL,
  `id_role` int(11) NOT NULL,
  PRIMARY KEY (`id_user`,`id_role`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0,01 sec)

mysql> 

It is obviously shown in the above output :

PRIMARY KEY (`id_user`,`id_role`)

So, the step taken is shown below :

1. Drop the table

mysql> drop table user_role;
Query OK, 0 rows affected (0,06 sec)
mysql>

2. Recreate the table as shown below :

mysql> create table user_role(id int not null auto_increment,id_user int not null, id_role int not null, primary key(id));
Query OK, 0 rows affected (0,12 sec)

mysql> 

3. Add foreign key for the id_user column as shown below :

mysql> alter table test add constraint fk_id_user foreign key(id_user) references user(id) on update cascade on delete cascade;
Query OK, 0 rows affected (0,07 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> 

3. Add foreign key for the id_role column as shown below :

mysql> alter table test add constraint fk_id_role foreign key(id_role) references role(id_role) on update cascade on delete cascade;
Query OK, 0 rows affected (0,08 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc user_role;

4. Describe the table structure as shown below :

+---------+---------+------+-----+---------+----------------+
| Field   | Type    | Null | Key | Default | Extra          |
+---------+---------+------+-----+---------+----------------+
| id      | int(11) | NO   | PRI | NULL    | auto_increment |
| id_user | int(11) | NO   | MUL | NULL    |                |
| id_role | int(11) | NO   | MUL | NULL    |                |
+---------+---------+------+-----+---------+----------------+
3 rows in set (0,00 sec)

mysql>

So, adding the primary key has already been finished upon solving the error message “Multiple primary key defined”.

WordPress dbDelta returns a SQL error when updating a table. It returns “Multiple primary key defined“.
I was stuck for two days on this problem. WordPress shown me following error message on plugin activation

The plugin generated 202 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.


I searched for the main cause. I edited WordPress core file to save the output that was being generated on plugin activation. I found WP returns following MySQL error on behind.

<div id=’error’>
<p class=’wpdberror’><strong>WordPress database error:</strong> [Multiple primary key defined]<br />
<code>ALTER TABLE wp_my_stat CHANGE COLUMN id `id` bigint(20) NOT NULL PRIMARY KEY auto_increment</code></p>
</div>

But I could not find the sql syntax error in my query. My query is bellow.

$my_stat_sql = "CREATE TABLE IF NOT EXISTS `$my_stat_table` (
	  `id` bigint(20) NOT NULL auto_increment,
	  `cid` bigint(20) NOT NULL,
	  `v_time` datetime NOT NULL,
	  `ip` varchar(20) NOT NULL,
	  PRIMARY KEY  (`id`)
	) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
	";

	dbDelta($my_stat_sql);

Are you see any error on above codes? probably not.

Finally I got the solution.

Actually WP dbDelta can not handle when you use PRIMARY KEY (`id`) with back-tick (`) any single or double quote , or space between columns names like PRIMARY KEY (“id, pid”).
I removed the back-ticks (`) from my query when assigning the primary keys. PRIMARY KEY (id). My issue has been solved. My new codes is bellow

$my_stat_sql = "CREATE TABLE IF NOT EXISTS `$my_stat_table` (
	  `id` bigint(20) NOT NULL auto_increment,
	  `cid` bigint(20) NOT NULL,
	  `v_time` datetime NOT NULL,
	  `ip` varchar(20) NOT NULL,
	  PRIMARY KEY  (id)
	) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
	";

	dbDelta($my_stat_sql);

More problem I found. My plugin returns error on installation yet. Got error : [Multiple primary key defined] ALTER TABLE my_stat_table ADD PRIMARY KEY (id)
After a long experiment I decided to use UNIQUE KEY.
Now I am using UNIQUE KEY id (id) instead of PRIMARY KEY (id)
because dbDelta were returning error “[Multiple primary key defined]”
Difference between PRIMARY KEY and UNIQUE KEY
Primary keys and unique keys are similar. A primary key is a column, or a combination of columns, that can uniquely identify a row. It is a special case of unique key. A table can have at most one primary key, but more than one unique key. When you specify a unique key on a column, no two distinct rows in a table can have the same value.
Read : Discussion 1 , Discussion 2

I saw my plugin table is not being updated with new column on plugin activation.
I stopped using “IF NOT EXISTS” with create table because, if I use this, dbdelta don’t update my table.
I removed all back tick(`) from all column name and table name to be more safe.

SO NOW MY FINAL ERROR FREE CODE IS :

$my_stat_sql = "CREATE TABLE IF NOT EXISTS $my_stat_table (
	  id bigint(20) NOT NULL auto_increment,
	  cid bigint(20) NOT NULL,
	  v_time datetime NOT NULL,
	  ip varchar(20) NOT NULL,
	  UNIQUE KEY id (id)
	) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
	";

	dbDelta($my_stat_sql);

Read more detail about WordPress dbDelta Function and core documentation about dbDelta and creating tables with plugin

Автор FAQ

3685 / 962 / 114

Регистрация: 10.01.2010

Сообщений: 2,550

1

02.07.2011, 22:28. Показов 27699. Ответов 3


SQL-запрос:

CREATE TABLE `v_sites` (
`ID` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`CODE` CHAR( 32 ) KEY ,
`NAME` VARCHAR( 512 )
)

Ответ MySQL:
#1068 — Multiple primary key defined

Где оно увидело здесь два PRIMARY KEY?



0



Vovan-VE

13207 / 6595 / 1041

Регистрация: 10.01.2008

Сообщений: 15,069

03.07.2011, 06:37

2

insideone, Он просто KEY после поля считает PRIMATY KEY’ем:

Код

column_definition:
    data_type [NOT NULL | NULL] [DEFAULT default_value]
      [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
      [COMMENT 'string'] [reference_definition]
      [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]
      [STORAGE {DISK|MEMORY|DEFAULT}]

The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

Если хотел UNIQUE KEY, то либо так:

SQL
1
2
3
4
5
CREATE TABLE `v_sites` (
  `ID` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `CODE` CHAR( 32 ) UNIQUE KEY,
  `NAME` VARCHAR( 512 )
)

либо так

SQL
1
2
3
4
5
6
CREATE TABLE `v_sites` (
  `ID` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `CODE` CHAR( 32 ),
  `NAME` VARCHAR( 512 ),
  UNIQUE KEY `CODE` (`CODE`)
)



1



insideone

Автор FAQ

3685 / 962 / 114

Регистрация: 10.01.2010

Сообщений: 2,550

03.07.2011, 14:02

 [ТС]

3

Цитата
Сообщение от Vovan-VE
Посмотреть сообщение

Он просто KEY после поля считает PRIMATY KEY’ем

Вот оно как… Да я в общем-то просто индекс хотел задать. Теперь понял что нужно так:

SQL
1
KEY `CODE` (`CODE`)



0



0 / 0 / 0

Регистрация: 19.10.2015

Сообщений: 10

23.10.2015, 21:00

4

А у меня эта ошибка «прошла» сама собой на следующий день. Даже не знала, что так бывает. Вчера искала инфу, как ее решить, но времени не хватило. Сегодня открыла базу — все отличненько! Как и не бывало проблемы.



0



Problem

When using a WordPress plugin you receive an error message which reads:

The plugin generated 4191 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.

When checking the event logs you see the error message:

WordPress database error: [Multiple primary key defined]
ALTER TABLE wp_table ADD PRIMARY KEY  (`id`)

Solution

The first error message is a generic message that indicates that an error has occured, there is very little use you can get out of this message.

The second message can be seen when you debug the plugin. You can use the Debug “unexpected output” During Plugin Activation plugin to help you.

The ‘WordPress database error: [Multiple primary key defined]’ error indicates an error in the use of the dbDelta, a core WordPress function which handles the management of the WordPress database.

The error is in the use of

ADD PRIMARY KEY  (`id`)

The column name is incorect or not properly formatted – in this example backticks have been used, which is not correct when using dbDelta.

To fix the issue you will need to:

1. Determine the plugin that is causing the issue

This can be done by disabling all the plugins until the issue is resolved.

When the error message is no longer appearing, re-activate the last plugin to confirm the errors have started again.

2. Determine what part of the plugin is causing the issue

dbDelta is typically ran when a plugin is activated, and sometimes when it is deactivated.

If this is the cause you will only see the error message whe the plugin is activated/deactivated.

You will need to read through the plugin’s PHP files to find where the dbDelta function is being used.

For example, you will see something like this:

dbDelta( $sql );

Above it you will find the $sql variable containing a database query.

For example:

$table = $wpdb->prefix . "table";
$sql = "CREATE TABLE ".$table." (
              `id` bigint(20) NOT NULL AUTO_INCREMENT,
              `Program_ID` int(11) NOT NULL,
              `Program_Code` varchar(10) NOT NULL,
              `Short_Name` varchar(40) NOT NULL,
              `Description` varchar(50) NOT NULL,
               PRIMARY  KEY  (`id`)
               ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
            
dbDelta( $sql );

3. Fix the cause of the issue

Where I’ve experienced this issue the cause was using backward ticks around the column names.

Backward ticks are normally used when using the phpMyAdmin database tool – but are not used when using dbDelta.

The fix here would be to remove the backward ticks. Note also that there is a DOUBLE SPACE between PRIMARY KEY and the column.

$table = $wpdb->prefix . "table";
$sql = "CREATE TABLE ".$table." (
               id bigint(20) NOT NULL AUTO_INCREMENT,
               Program_ID int(11) NOT NULL,
               Program_Code varchar(10) NOT NULL,
               Short_Name varchar(40) NOT NULL,
               Description varchar(50) NOT NULL,
               PRIMARY  KEY  (id)
               ) ENGINE=InnoDB DEFAULT CHARSET=utf8";
            
dbDelta( $sql );

See the creating tables with plugins on the WordPress website for more information on how to correctly use dbDelete.


Понравилась статья? Поделить с друзьями:
  • Multiple crashes detected epic games как исправить на русском
  • Multiple comparison error
  • Mse среднеквадратическая ошибка
  • Multiplayer is disabled please check your microsoft account как исправить
  • Multipath error getting device debian