简体   繁体   English

更新表以使用两个外键生成主键

[英]Update table to make primary key out of two foreign keys

Have a table sample_tag which already exists with 1000's of entries.有一个表sample_tag已经存在 1000 个条目。

It consists of two foreign keys, sample_id and tag_id .它由两个外键sample_idtag_id

However, the database is allowing duplicate sample_id/tag_id records to be created.但是,数据库允许创建重复的sample_id/tag_id记录。

Without creating a new table, is there a SQL statement to update the sample_tag table such that the two foreign keys, together, function as its primary key?在不创建新表的情况下,是否有一条 SQL 语句来更新sample_tag表,使两个外键一起 function 作为其主键?

Database is MySQL using phpMyAdmin数据库是 MySQL 使用 phpMyAdmin

The main challenge is how you resolve the duplicates.主要挑战是如何解决重复项。 If there are already duplicate keys, then you'll need to address these as a separate step (either deleting the duplicate, or merging any other columns as you see fit).如果已经有重复的键,那么您需要将它们作为一个单独的步骤来解决(删除重复的,或者合并任何其他您认为合适的列)。

To check for duplicates, try:要检查重复项,请尝试:

SELECT sample_id, tag_id, COUNT( * )
FROM sample_tag
GROUP BY sample_id, tag_id;

If there are none, then you can go ahead and delete any existing primary key, and create a new one.如果没有,那么您可以提前 go 并删除任何现有的主键,并创建一个新的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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