根据另一个表中的值,DROP表的列

时间:2013-12-07 10:47:33

标签: mysql sql alter-table

我有像

这样的表格

表A

field1  | field2 | field3 | field4 | field5 

表B

id    | field_names
--------------------
1       field2
2       field3

我必须从Table A删除field2和field3(表示Table B中的字段名称。)

有没有办法删除Table B中出现的字段名称。我无法手动删除字段。

提前致谢

3 个答案:

答案 0 :(得分:3)

这会有所帮助:

SELECT @s := CONCAT('ALTER TABLE tableA DROP COLUMN ', GROUP_CONCAT(field_names SEPARATOR ', DROP COLUMN '), ';') FROM tableB;
PREPARE stmt FROM @s;
EXECUTE @s;

答案 1 :(得分:1)

不确定为什么需要这个。无论如何MySQL没有这样的功能。但如果你真的想这样做,执行以下查询并执行每一行。

SELECT CONCAT('ALTER TABLE TableA DROP ', field_names, ';') FROM TableB;

用于PHP的示例,(省略所有错误检查)

$query = "SELECT CONCAT('ALTER TABLE TableA DROP ', field_names, ';') AS stmt FROM TableB;";

$result = mysqli_query($query);

while ($row = mysqli_fetch_assoc($result))
{
    mysqli_query($rows['stmt']);
}

答案 2 :(得分:1)

首先创建一个程序:

DELIMITER //
CREATE PROCEDURE deleteTableAColumns()
BEGIN
    DECLARE columnToDelete VARCHAR(16);
    DECLARE done INT DEFAULT FALSE;
    DECLARE columnsToDeleteCur CURSOR FOR SELECT field_names FROM tableB;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    OPEN columnsToDeleteCur;
    read_loop: LOOP 
        FETCH columnsToDeleteCur INTO columnToDelete;
        IF done THEN
            LEAVE read_loop;
        END IF;
        SET @dropColumnQuery = CONCAT('ALTER TABLE tableA DROP ', columnToDelete, ';');
        PREPARE dropColumnQueryStatement FROM @dropColumnQuery;
        EXECUTE dropColumnQueryStatement;
        DEALLOCATE PREPARE dropColumnQueryStatement; 
    END LOOP;
    CLOSE columnsToDeleteCur;
END
//
DELIMITER ;

然后在您想要执行它时调用该过程:

CALL deleteTableAColumns();