我正在尝试从我正在使用Handsontable的MySQL表中删除一个列。当我从Handsontable中删除一列时,我可以使用afterRemoveCol()
回调获取列的索引:
afterRemoveCol: function (index, amount) {
alert(index +' amount: '+amount);
}
我想使用以下内容从MySQL表中使用此回调函数返回的列号(n
)删除列:
ALTER TABLE tbl_Blah DROP COLUMN n;
所以,如果我想从MySQL表中删除#3列,我将如何仅使用列号来执行此操作?
答案 0 :(得分:1)
SQL中的SQL可以使用information_schema.columns中的ordinal_position生成drop语句。
mysql test> create table test.tab (col1 char(1), col2 char(1), col3 char(1), col4 char(1), col5 char(1));
Query OK, 0 rows affected (0.01 sec)
mysql test> desc test.tab;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| col1 | char(1) | YES | | NULL | |
| col2 | char(1) | YES | | NULL | |
| col3 | char(1) | YES | | NULL | |
| col4 | char(1) | YES | | NULL | |
| col5 | char(1) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
5 rows in set (0.00 sec)
此查询正在生成要删除第三列的语句...
mysql test> select concat('alter table ',table_schema,'.',table_name,' drop column ',column_name,';') as query1 from information_schema.columns where table_schema='test' and table_name='tab' and ordinal_position=3;
+----------------------------------------+
| query1 |
+----------------------------------------+
| alter table test.tab drop column col3; |
+----------------------------------------+
1 row in set (0.00 sec)
现在运行预计的命令......
mysql test> alter table test.tab drop column col3;
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
列定义已从表中删除。
mysql test> desc test.tab;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| col1 | char(1) | YES | | NULL | |
| col2 | char(1) | YES | | NULL | |
| col4 | char(1) | YES | | NULL | |
| col5 | char(1) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
4 rows in set (0.01 sec)
答案 1 :(得分:1)
要添加到RMathis答案,您可以通过使用SET与PREPARE and EXECUTE结合定义DROP字符串来在SQL中执行所有操作
MySQL 5.6架构设置:
CREATE TABLE Table1
(`col1` varchar(1),
`col2` varchar(1),
`col3` varchar(1),
`col4` varchar(1),
`col5` varchar(1))
;
set @col = (select column_name
from information_schema.columns
where table_name='table1' and ordinal_position=3);
SET @s = CONCAT("alter table table1 drop column ", @col);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
查询1 :
desc table1
<强> Results 强>:
| COLUMN_NAME | COLUMN_TYPE | IS_NULLABLE | COLUMN_KEY | COLUMN_DEFAULT | EXTRA |
|-------------|-------------|-------------|------------|----------------|-------|
| col1 | varchar(1) | YES | | (null) | |
| col2 | varchar(1) | YES | | (null) | |
| col4 | varchar(1) | YES | | (null) | |
| col5 | varchar(1) | YES | | (null) | |
答案 2 :(得分:0)
使用与电子表格完全对应的数字/字母命名它们(数据库镜像电子表格中的列)。
然后你就可以使用常规的ALTER TABLE ... DROP COLUMN。