如何将列数据移动到另一个 table 并将其 ID 设置为第一个 table 中的外键列?

how can i move column data to another table and set its id to foreign key column in first table?

我有 table 应用程序,其中一个列名为 allowed_command , 然后我创建另一个 table application_command 并想分开 allowed_command 列并移动到第二个 table 'application_command' 此外,应用程序 table 具有来自 application_command 的外键 所以,我需要将 allowed_command 的值复制到 application_command table 然后将其 id 放在第一个 table

要移动列数据,您可以使用 INSERT INTO SELECT

INSERT INTO application_command(allowed_command) ---suppose this is the name of the second table
SELECT 
   allowed_command 
FROM 
   application   ---If you have a where condition you can add, if not remove the where condition
WHERE    
   condition;

同样的事情也可以用 id 来完成。

INSERT INTO application (id_application_command) 
SELECT 
   id
FROM 
   application_command ---If you have a where condition you can add, if not remove the where condition
WHERE    
   condition;

单独的新 table 创作毫无意义。我建议您在数据复制期间删除它并创建新实例。

第 1 步。新建 table 并将数据复制到其中。

CREATE TABLE application_command ( 
    application_command_id BIGINT AUTO_INCREMENT PRIMARY KEY,
    allowed_command VARCHAR(255) )
SELECT DISTINCT allowed_command
FROM application;

第 2 步。为外键创建列。

ALTER TABLE application 
    ADD COLUMN application_command_id BIGINT,
    ADD FOREIGN KEY fk_allowed_command (application_command_id)
        REFERENCES application_command (application_command_id)
        ON UPDATE CASCADE ON DELETE SET NULL;

步骤 3. 设置关系值。

UPDATE application
  JOIN application_command USING (allowed_command)
SET application.application_command_id = application_command.application_command_id;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=60661aae250012bcc4c9f72c1f6e2cb0

现在您可以删除 application.allowed_command 列。