简体   繁体   English

以0开头的数据库数字字段

[英]Database numeric field starting with 0

I am using a field named as area_code that has int data-type in MySQL. 我正在使用一个名为area_code的字段,该字段在MySQL中具有int数据类型。 But it doesn't allow me to store exact values like 0781, 0727, 0788 Bcoz they are starting with 0. It stores the values as 781, 727 and 788 ie it truncates 0 from the values and save it. 但是它不允许我存储精确的值,如0781,0727,0788 Bcoz,它们从0开始。它存储的值分别为781、727和788,即从值中截断0并保存。

Please help me.. 请帮我..

Area codes are not numbers, but text (which contains digits only). 区号不是数字,而是文本(仅包含数字)。 Declare area_code as a varchar field of appropriate size. 将area_code声明为适当大小的varchar字段。

drop table if exists foo;
create table foo
(
area_code smallint(4) unsigned zerofill not null default 0
)
engine=innodb;

insert into foo (area_code) values (781),(727);

select * from foo;
+-----------+
| area_code |
+-----------+
|      0781 |
|      0727 |
+-----------+

http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html

使用基于字符的数据类型,而不是数字数据类型。

使用VARCHAR,因为您不需要对区号进行任何算术运算

if you want your result as 4 digits you can maybe do it in this way: 如果您希望结果为4位数字,则可以按以下方式进行操作:

select lpad(area_code, 4, '0') from zipcode_list;

now you can store the 3 numbers in your database and returning the zero before. 现在,您可以将3个数字存储在数据库中,然后返回零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM