2

有没有一种快速简便的方法可以将 varchar/char 转换为枚举?我试图这样做,但它不起作用

alter table zipcodes add column state_short_enum enum(
    (select state_short from zipcodes group by state_short)
)

我收到此错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 
'(select state_short from zipcodes group by state_short))' at line 1
4

2 回答 2

1

枚举值必须是文字,因此您不能使用用户变量或标量子查询。可能您必须将ALTER语句创建为字符串。

例子:

SET @codes := CONCAT((SELECT GROUP_CONCAT(CONCAT("'", state_short, "'")) FROM zipcodes), "'");
SET @alter_sql := CONCAT('ALTER TABLE `zipcodes` ADD `state_short_enum` ENUM(', @codes, ')');
PREPARE stmt FROM @alter_sql;
EXECUTE stmt;
于 2013-03-19T02:50:27.820 回答
0

我知道,这已经是过时的问题,但我在尝试解决类似问题时发现了它。在 MySQL 8.0 之前的版本中,有一个' procedure analyze ',它很容易使用:

select * from t procedure analyse()\G

它在“Optimal_fieldtype”列中为您提供最佳字段类型。你可以直接在 alter 中使用这个结果:

alter table t change column col1 enum(...) not null;

当然,在进行更改之前应采取所有预防措施(进行备份,确保在更改期间保持在表上的锁不会破坏正常活动)。

于 2017-05-31T04:18:30.973 回答