【问题标题】:mysql data type confusionmysql数据类型混淆
【发布时间】:2011-02-01 13:59:45
【问题描述】:

所以这更像是一个关于 MySQL 数据类型的一般性问题。在此示例中,我想正确存储 5 位美国邮政编码 (zip_code)。

一个县有 10 个不同的城市和 5 个不同的邮政编码。

city   | zip code
-------+----------
city 0 | 33333
city 1 | 11111
city 2 | 22222
city 3 | 33333
city 4 | 44444
city 5 | 55555
city 6 | 33333
city 7 | 33333
city 8 | 44444
city 9 | 22222

我通常会将这样的表构造为 varchar(50), int(5) 而不会三思而后行。

(1) 如果我们想确保这个表只有 5 个不同的邮政编码之一,我们应该使用 enum 数据类型,对吗?

现在想一个更大范围的类似场景。在一个州,有 500 个城市,有 418 个不同的邮政编码。

(2) 我应该将 418 邮政编码存储为 enum 数据类型还是 int 并创建另一个表以供参考?

【问题讨论】:

标签: mysql types enums int sqldatatypes


【解决方案1】:

邮政编码应该是整数...MEDIUMINT 是您要查找的内容。几千个不同的值对于 ENUM 来说不是一个好主意 - 除了 IIRC ENUM 被限制为 64 个不同的值。

您可以创建另一个名为city 的表来存储城市。结构将非常简单:只需标准 ID + 城市名称列 - VARCHAR(50) 就足够了。 当然,您必须将city_id 添加到邮政编码表(附加外键)。

【讨论】:

    【解决方案2】:

    如果 smallint unsigned (0 到 65535) 太小,则更改为 mediumint。

    create table city(
     city_id smallint unsigned not null auto_increment primary key,
     name varchar(255) not null
    )engine=innodb;
    
    create table city_zip(
     city_id smallint unsigned not null,
     zip_code smallint unsigned not null,
     primary key (city_id, zip_code)
    )engine=innodb;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-14
      • 2017-12-24
      • 1970-01-01
      • 2015-03-03
      • 2013-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多