设计数据库之经验谈_MySQL
数据库设计经验谈
数据库模型的设计是否合理会极大影响系统的使用性能。笔者依据多年来设计和使用数据库的经验,提出以下一些设计原则,供同仁们参考。
慎用游标(Cursor)
游标提供了对特定集合中逐行扫描的手段,一般使用游标来逐行遍历数据,根据取出数据条件的不同进行不同的操作。而对于多表和大表中定义的游标(大的数据集合)循环很容易使程序进入一个漫长的等待甚至死机,笔者在某市“住房公积金管理系统”进行日终账户滚积数计息处理时,对一个10万个账户的游标处理时导致程序进入了一个无限期的等待(后经测算需48小时才能完成)(硬件环境:Alpha/4000 128MB RAM ,SCO Unix ,Sybase 11.0)。经修改程序并改用UPDATE语句后,该处理过程得以在20分钟之内完成。示例如下:
Declare Mycursor cursor for select count—no from COUNT
Open Mycursor
Fetch Mycursor into @vcount—no
While (@@sqlstatus=0)
Begin
If @vcount—no=′ ′ 条件1
操作1
If @vcount—no=′ ′ 条件2
操作2
...
Fetch Mycursor into @vcount—no
End
...
改为
Update COUNT set 操作1 for 条件1
Update COUNT set 操作2 for 条件2
...
在某些必须使用游标的场合,可考虑将符合条件的数据行转入临时表中,再对临时表定义游标进行操作,这样,可使性能得到明显提高。笔者在某地市“电信收费系统”数据库后台程序设计中,对一个表(3万行中符合条件的30多行数据)进行游标操作(硬件环境:PC服务器,PⅡ266 64MB RAM ,Windows NT4.0 MS SQL Server 6.5)。
示例如下:
Create #tmp /* 定义临时表 */
( 字段1
字段2
... )
Insert into #tmp select * from TOTAL where 条件
Declare Mycursor cursor for select * from #tmp /*对临时表定义游标*/
...
索引(Index)的使用技巧
创建索引一般有两个目的:维护被索引列的惟一性和提供快速访问表中数据的策略。大型数据库有两种索引,即簇索引和非簇索引,一个没有簇索引的表是按堆结构存储数据,所有的数据均添加在表的尾部;而建立了簇索引的表,其数据在物理上会按照簇索引键的顺序存储,一个表只允许有一个簇索引,因此,根据B树结构,可以理解添加任何一种索引均能提高按索引列查询的速度,但与此同时会降低插入、更新、删除操作的性能,尤其是当填充因子(Fill Factor)较大时。所以对索引较多的表进行频繁的插入、更新、删除操作时,建表和索引时应设置较小的填充因子,以便在各数据页中留下较多的自由空间,减少页分割及重新组织的工作。
数据的一致性和完整性
为了保证数据库的一致性和完整性,设计人员往往会设计过多的表间关联(Relation),尽可能地降低数据冗余。表间关联是一种强制性措施,建立后,对父表(Parent Table)和子表(Child Table)的插入、更新、删除操作均要占用系统的开销,另外,最好不要用Identify 属性字段作为主键与子表关联。如果数据冗余低,数据的完整性容易得到保证,但增加了表间连接查询的操作。为了提高系统的响应时间,合理的数据冗余也是必要的。使用规则(Rule)和约束(Check)来防止系统操作人员误输入造成数据的错误是,设计人员的另一种常用手段,但是,不必要的规则和约束也会占用系统的不必要开销,需要注意的是,约束对数据的有效性验证要比规则快。所有这些,设计人员在设计阶段应根据系统操作的类型、频度加以均衡考虑。
事务的陷阱
事务是在一次性完成的一组操作。虽然这些操作是单个的操作,SQL Server能够保证这组操作要么全部都完成,要么一点儿都不做。正是大型数据库的这一特性,使得数据的完整性得到了极大的保证。
众所周知,SQL Server为每个独立的SQL语句都提供了隐含的事务控制,使得每个DML的数据操作得以完整提交或回滚,但是SQL Server还提供了显式事务控制语句,如:
BEGIN TRANSACTION 开始一个事务
COMMIT TRANSACTION 提交一个事务
ROLLBACK TRANSACTION 回滚一个事务
事务可以嵌套,可以通过全局变量@@trancount检索到连接的事务处理嵌套层次。要特别注意的是,每个显示或隐含的事物开始都使得该变量加1,每个事务的提交使该变量减1,每个事务的回滚都会使得该变量置0,而只有当该变量为0时的事务提交(最后一个提交语句时),才把物理数据写入磁盘。
数据类型的选择
数据类型的合理选择对于数据库的性能和操作具有很大的影响,有关这方面的书籍也有不少的阐述,笔者这里主要介绍几点经验:
1. Identify字段不要作为表的主键与其它表关联,这将会影响到该表的数据迁移。
2. Text 和Image字段属指针型数据,主要用来存放二进制大型对象(BLOB)。这类数据的操作相比其它数据类型较慢,因此要避开使用。
3. 日期型字段的优点是有众多的日期函数支持,因此,在日期的大小比较、加减操作上非常简单。但是,在按照日期作为条件的查询操作也要用函数,相比其它数据类型速度上就慢许多,因为用函数作为查询的条件时,服务器无法用先进的性能策略来优化查询而只能进行表扫描遍历每行。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Recently, the military circle has been overwhelmed by the news: US military fighter jets can now complete fully automatic air combat using AI. Yes, just recently, the US military’s AI fighter jet was made public for the first time and the mystery was unveiled. The full name of this fighter is the Variable Stability Simulator Test Aircraft (VISTA). It was personally flown by the Secretary of the US Air Force to simulate a one-on-one air battle. On May 2, U.S. Air Force Secretary Frank Kendall took off in an X-62AVISTA at Edwards Air Force Base. Note that during the one-hour flight, all flight actions were completed autonomously by AI! Kendall said - "For the past few decades, we have been thinking about the unlimited potential of autonomous air-to-air combat, but it has always seemed out of reach." However now,

According to news on July 12, the Honor Magic V3 series was officially released today, equipped with the new Honor Vision Soothing Oasis eye protection screen. While the screen itself has high specifications and high quality, it also pioneered the introduction of AI active eye protection technology. It is reported that the traditional way to alleviate myopia is "myopia glasses". The power of myopia glasses is evenly distributed to ensure that the central area of sight is imaged on the retina, but the peripheral area is imaged behind the retina. The retina senses that the image is behind, promoting the eye axis direction. grow later, thereby deepening the degree. At present, one of the main ways to alleviate the development of myopia is the "defocus lens". The central area has a normal power, and the peripheral area is adjusted through optical design partitions, so that the image in the peripheral area falls in front of the retina.

70B model, 1000 tokens can be generated in seconds, which translates into nearly 4000 characters! The researchers fine-tuned Llama3 and introduced an acceleration algorithm. Compared with the native version, the speed is 13 times faster! Not only is it fast, its performance on code rewriting tasks even surpasses GPT-4o. This achievement comes from anysphere, the team behind the popular AI programming artifact Cursor, and OpenAI also participated in the investment. You must know that on Groq, a well-known fast inference acceleration framework, the inference speed of 70BLlama3 is only more than 300 tokens per second. With the speed of Cursor, it can be said that it achieves near-instant complete code file editing. Some people call it a good guy, if you put Curs

Last week, amid the internal wave of resignations and external criticism, OpenAI was plagued by internal and external troubles: - The infringement of the widow sister sparked global heated discussions - Employees signing "overlord clauses" were exposed one after another - Netizens listed Ultraman's "seven deadly sins" Rumors refuting: According to leaked information and documents obtained by Vox, OpenAI’s senior leadership, including Altman, was well aware of these equity recovery provisions and signed off on them. In addition, there is a serious and urgent issue facing OpenAI - AI safety. The recent departures of five security-related employees, including two of its most prominent employees, and the dissolution of the "Super Alignment" team have once again put OpenAI's security issues in the spotlight. Fortune magazine reported that OpenA

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

According to news on July 19, Xiaomi MIX Fold 4, the first flagship folding new phone, was officially released tonight and is equipped with a "three-dimensional special-shaped battery" for the first time. According to reports, Xiaomi MIX Fold4 has achieved a major breakthrough in battery technology and designed an innovative "three-dimensional special-shaped battery" specifically for folding screens. Traditional folding screen devices mostly use conventional square batteries, which have low space utilization efficiency. In order to solve this problem, Xiaomi did not use the common winding battery cells, but developed a new lamination process to create a new form of battery, which greatly improved the space utilization. Battery Technology Innovation In order to accurately alternately stack positive and negative electrode sheets and ensure the safe embedding of lithium ions, Xiaomi has developed a new ultrasonic welding machine and lamination machine to improve welding and cutting accuracy.

According to news on May 8, Apple’s new iPad Pro/Air tablets have been released. According to Apple’s official website, the new iPad Pro and iPad Air no longer support the second-generation Apple Pencil released in 2018, but only support Apple Pencil Pro and Apple Pencil (USB- C). Apple Pencil (USB-C) will be released in November 2023. This stylus maintains the same pixel-level accuracy, low latency, and tilt-angle sensing features as the first and second-generation Apple Pencil, while eliminating pressure sensitivity. function and does not support wireless charging. Its price is 649 yuan. And the newly released ApplePe

According to news on July 29, the Honor X60i mobile phone is officially on sale today, starting at 1,399 yuan. In terms of design, the Honor X60i mobile phone adopts a straight screen design with a hole in the center and almost unbounded ultra-narrow borders on all four sides, which greatly broadens the field of view. Honor X60i parameters Display: 6.7-inch high-definition display Battery: 5000mAh large-capacity battery Processor: Dimensity 6080 processor (TSMC 6nm, 2x2.4G A76+6×2G A55) System: MagicOS8.0 system Other features: 5G signal enhancement, smart capsule, under-screen fingerprint, dual MIC, noise reduction, knowledge Q&A, photography capabilities: rear dual camera system: 50 million pixels main camera, 2 million pixels auxiliary lens, front selfie lens: 8 million pixels, price: 8GB
