【问题标题】:How to alter composite primary key to add additional column如何更改复合主键以添加附加列
【发布时间】:2017-10-02 11:26:12
【问题描述】:

让我们支持我有一个迁移,我们称之为001_Create_organization_users.php 有两列,X,Y,它们都是一个组合的 PK:

<?php

namespace Fuel\Migrations;

class Create_organizations_users
{
    public function up()
    {
        \DBUtil::create_table('organizations_users', array(
            'X' => array('constraint' => 11, 'type' => 'int'),
            'Y' => array('constraint' => 11, 'type' => 'int')
        ), array('X', 'Y')); // Primary Key
    }
// Other functions
}

然后我用不同的迁移向该表添加一列,我们称之为002_Add_column_to_organization_users.php

<?php

namespace Fuel\Migrations;

class Add_column_to_organization_users.php
{
    public function up()
    {
        $fields = array(
            'Z' => array(
                'constraint' => 11, 'type' => 'int'),
        );

 \DBUtil::add_fields('organizations_users', $fields);
 //....
}

我能否以某种方式编辑该迁移,以便我可以将列“Z”添加为具有先前输入的键的主键,以便我的最终主键是X,Y,Z

【问题讨论】:

  • 您是说需要将主要设为X,Y,Z 而不是X,Y 吗?
  • @Ravi 是的,在我通过第二次迁移添加列 Z 后,我需要将该字段添加为现有主键的一部分。

标签: mysql sql primary-key composite-primary-key alter


【解决方案1】:

既然您已经创建了PRIMARY KEY,那么您需要先删除它,然后使用一组新的列创建一个新的。

ALTER TABLE <table_name> DROP PRIMARY KEY, ADD PRIMARY KEY(X, Y, Z);

【讨论】:

  • 对于任何想知道这是正确答案的人,您所要做的就是使用 \DB::query('ALTER TABLE &lt;table_name&gt; DROP PRIMARY KEY, ADD PRIMARY KEY(X, Y, Z);' 运行以下查询
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 2012-02-10
  • 2011-01-21
  • 2010-11-23
相关资源
最近更新 更多