문제

I have tables like,

Table A

field1  | field2 | field3 | field4 | field5 

Table B

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

I have to delete field2 and field3 from Table A ( means field names in Table B ).

Is there any way to drop field names which present in Table B. I can't delete the fields manually.

Thanks in advance

도움이 되었습니까?

해결책 2

Not sure why you need this. anyway MySQL has no such feature. but if you want really do that, execute following query and execute each rows.

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

for examples with PHP, (all error check is omitted)

$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']);
}

다른 팁

This would help:

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

First create a procedure:

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 ;

Then call the procedure whenever you want to execute it:

CALL deleteTableAColumns();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top