search
HomeDatabaseMysql TutorialMySQL的数据类型和建库策略

无论是在小得可怜的免费数据库空间或是大型电子商务网站,合理的设计表结构、充分利用空间是十分必要的。这就要求我们对数据库系统的常用数据类型有充分的认识。下面我就将我的一点心得写出来跟大家分享。 一、数字类型。数字类型按照我的分类方法分为三类:

无论是在小得可怜的免费数据库空间或是大型电子商务网站,合理的设计表结构、充分利用空间是十分必要的。这就要求我们对数据库系统的常用数据类型有充分的认识。下面我就将我的一点心得写出来跟大家分享。

一、数字类型。数字类型按照我的分类方法分为三类:整数类、小数类和数字类。
我所谓的“数字类”,就是指DECIMAL和NUMERIC,它们是同一种类型。它严格的说不是一种数字类型,因为他们实际上是将数字以字符串形式保存的;他的值的每一位(包括小数点)占一个字节的存储空间,因此这种类型耗费空间比较大。但是它的一个突出的优点是小数的位数固定,在运算中不会“失真”,所以比较适合用于“价格”、“金额”这样对精度要求不高但准确度要求非常高的字段。
小数类,即浮点数类型,根据精度的不同,有FLOAT(单精度)和DOUBLE(双精度)两种。它们的优势是精确度,FLOAT可以表示绝对值非常小、小到约 1.17E-38 (0.000...0117, 小数点后面有37个零)的小数,而DOUBLE更是可以表示绝对值小到约 2.22E-308 (0.000...0222, 小数点后面有307个零)的小数。FLOAT类型和DOUBLE类型占用存储空间分别是4字节和8字节。如果需要用到小数的字段,精度要求不高的,当然用FLOAT了!可是说句实在话,我们“民用”的数据,哪有要求精度那么高的呢?这两种类型至今我没有用过——我还没有遇到适合于使用它们的事例。
用的最多的,最值得精打细算的,是整数类型。从只占一个字节存储空间的TINYINT到占8个字节的BIGINT,挑选一个“够用”并且占用存储空间最小的类型是设计数据库时应该考虑的。TINYINT、SMALLINT、MEDIUMINT、INT和BIGINT占用存储空间分别为1字节、2字节、3字节、4字节和8字节,就无符号的整数而言,这些类型能表示的最大整数分别为255、65535、16777215、4294967295和18446744073709551615。如果用来保存用户的年龄(举例来说,数据库中保存年龄是不可取的),用TINYINT就够了;九城的《纵横》里,各项技能值,用SMALLINT也够了;如果要用作一个肯定不会超过16000000行的表的AUTO_INCREMENT的IDENTIFY字段,当然用 MEDIUMINT 不用 INT ,试想,每行节约一个字节,16000000行可以节约10兆多呢!

二、日期时间类型。
日期和时间类型比较简单,无非是 DATE、TIME、DATETIME、TIMESTAMP和YEAR等几个类型。只对日期敏感,而对时间没有要求的字段,就用DATE而不用DATETIME是不用说的了;单独使用时间的情况也时有发生——使用TIME;但最多用到的还是用DATETIME。在日期时间类型上没有什么文章可做,这里就不再详述。

三、字符(串)类型。
不要以为字符类型就是 CHAR !CHAR和VARCHAR的区别在于CHAR是固定长度,只要你定义一个字段是CHAR(10),那么不论你存储的数据是否达到了10个字节,它都要占去10个字节的空间;而VARVHAR则是可变长度的,如果一个字段可能的值是不固定长度的,我们只知道它不可能超过10个字符,把它定义为 VARCHAR(10)是最合算的,VARCHAR 类型的实际长度是它的值的(实际长度+1)。为什么“+1”呢?这一个字节用于保存实际使用了多大的长度呀!从这个“+1”中也应该看到,如果一个字段,它的可能值最长是10个字符,而多数情况下也就是用到了10个字符时,用VARCHAR就不合算了:因为在多数情况下,实际占用空间是11个字节,比用CHAR(10)还多占用一个字节!
举个例子,就是一个存储股票名称和代码的表,股票名称绝大部分是四个字的,即8个字节;股票代码,上海的是六位数字,深圳的是四位数字。这些都是固定长度的,股票名称当然要用 CHAR(8) ;股票代码虽然是不固定长度,但如果使用VARVHAR(6),一个深圳的股票代码实际占用空间是5个字节,而一个上海的股票代码要占用7个字节!考虑到上海的股票数目比深圳的多,那么用VARCHAR(6)就不如CHAR(6)合算了。
虽然一个CHAR或VARVHAR的最大长度可以到255,我认为大于20的CHAR是几乎用不到的——很少有大于20个字节长度的固定长度的东东吧?不是固定长度的就用VARCHAR!大于100的VARCHAR也是几乎用不到的——比这更大的用TEXT就好了。TINYTEXT,最大长度为255,占用空间也是(实际长度+1);TEXT,最大长度65535,占用空间是(实际长度+2);MEDIUMTEXT,最大长度16777215,占用空间是(实际长度+3);LONGTEXT,最大长度4294967295,占用空间是(实际长度+4)。为什么“+1”?“+2”?“+3”?“+4”?你要是还不知道就该打PP了。这些可以用在论坛啊、新闻啊,什么的,用来保存文章的正文。根据实际情况的不同,选择从小到大的不同类型。

四、枚举和集合类型。
枚举(ENUM)类型,最多可以定义65535种不同的字符串从中做出选择,只能并且必须选择其中一种,占用存储空间是一个或两个字节,由枚举值的数目决定;集合(SET)类型,最多可以有64个成员,可以选择其中的零个到不限定的多个,占用存储空间是一个到八个字节,由集合可能的成员数目决定。
举个例子来说,在SQLServer中,你可以节约到用一个Bit类型来表示性别(男/女),但MySQL没有Bit,用TINTINT?不,可以用ENUM(帅哥,美眉)!只有两种选择,所以只需一个字节——跟TINYINT一样大,但却可以直接用字符串帅哥和美眉来存取。真是太方便啦!

好了,MySQL的数据类型介绍得差不多,我的建库策略也随着介绍数据类型介绍给大家一些。但这只是其中一部分,篇幅有限,不能再细说;其他的,就靠各人在对数据类型理解的基础上,多多实践、多多讨论。


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.