MySQL由于它本身的小巧和操作的高效,在数据库应用中越来越多的被采用。作为LAMP(或WAMP)开发中的重要一环,MySQL值得PHP开发者的重视和认真学习。
1. 每一行命令都是用分号 (;) 作为结束
对于 MySQL ,第一件你必须牢记的是它的每一行命令都是用分号 (;) 作为结束的,但当一行 MySQL 被插入在 PHP 代码中时,最好把后面的分号省略掉,例如:
mysql_query ("INSERT INTO tablename (first_name, last_name) VALUES ('$first_name', $last_name')");
这是因为 PHP 也是以分号作为一行的结束的,额外的分号有时会让 PHP 的语法分析器搞不明白,所以还是省略掉的好。在这种情况下,虽然省略了分号,但是 PHP 在执行 MySQL 命令时会自动的帮你加上的。
2. 采用关联数组存取查询结果
看下面的例子:
<ol class="dp-c"> <li class="alt"><span><span class="vars">$connection</span><span> = mysql_connect(</span><span class="string">"localhost"</span><span>, </span><span class="string">"albert"</span><span>, </span><span class="string">"shhh"</span><span>); </span></span></li> <li><span>mysql_select_db(<span class="string">"winestore"</span><span>, </span><span class="vars">$connection</span><span>); </span></span></li> <li class="alt"><span><span class="vars">$result</span><span> = mysql_query("SELECT cust_id, surname, </span></span></li> <li><span>firstname FROM customer", <span class="vars">$connection</span><span>); </span></span></li> <li class="alt"><span> </span></li> <li><span><span class="keyword">while</span><span> (</span><span class="vars">$row</span><span> = mysql_fetch_array(</span><span class="vars">$result</span><span>)) </span></span></li> <li class="alt"><span>{ </span></li> <li><span><span class="func">echo</span><span> </span><span class="string">"ID:t{$row["</span><span>cust_id</span><span class="string">"]}n"</span><span>; </span></span></li> <li class="alt"><span><span class="func">echo</span><span> </span><span class="string">"Surnamet{$row["</span><span>surname</span><span class="string">"]}n"</span><span>; </span></span></li> <li><span><span class="func">echo</span><span> </span><span class="string">"First name:t{$row["</span><span>firstname</span><span class="string">"]}nn"</span><span>; </span></span></li> <li class="alt"><span>} </span></li> </ol>
函数 mysql_fetch_array() 把查询结果的一行放入数组,可以同时用两种方式引用,例如 cust_id 可以同时用下面两种方式:$row["cust_id"] 或者$row[0] 。显然,前者的可读性要比后者好多了。
在多表连查中,如果两个列名字一样,最好用别名分开:
<ol class="dp-c"> <li class="alt"><span><span>SELECT winery.name AS wname, region.name AS rname, FROM winery, region WHERE winery.region_id = region.region_id; </span></span></li> <li><span> </span></li> <li class="alt"><span>列名的引用为:<span class="vars">$row</span><span>[</span><span class="string">"wname"</span><span>] 和 </span><span class="vars">$row</span><span>[</span><span class="string">"rname"</span><span>] </span></span></li> </ol>
在指定表名和列名的情况下,只引用列名:
<ol class="dp-c"> <li class="alt"><span><span>SELECT winery.region_id </span></span></li> <li><span>FROM winery </span></li> <li class="alt"><span>列名的引用为: <span class="vars">$row</span><span>[</span><span class="string">"region_id"</span><span>] </span></span></li> </ol>
聚集函数的引用就是引用名:
<ol class="dp-sql"> <li class="alt"><span><span class="keyword">SELECT</span><span> </span><span class="func">count</span><span>(*) </span></span></li> <li class="alt"><span><span class="keyword">FROM</span><span> customer; </span></span></li> <li class="alt"><span>列名的引用为: $row[<span class="string">"count(*)"</span><span>] </span></span></li> </ol>
3. TEXT、DATE、和 SET 数据类型
MySQL 数据表的字段必须有定义一个数据类型。这有大约 25 种选择,大部分都是直接明了的,就不多费口舌了。但有几个有必要提一下。
TEXT 不是一种数据类型,虽然可能有些书上是这么说的。它实际上应该是“ LONG VARCHAR ”或者“ MEDIUMTEXT ”。
DATE 数据类型的格式是 YYYY-MM-DD ,比如: 1999-12-08 。你可以很容易的用 date 函数来得到这种格式的当前系统时间: date("Y-m-d") 并且,在 DATA 数据类型之间可以作减法,得到相差的时间天数:
<ol class="dp-c"><li class="alt"><span><span class="vars">$age</span><span> = (</span><span class="vars">$current_date</span><span> - </span><span class="vars">$birthdate</span><span>); </span></span></li></ol>
集合 SET 是一个有用的数据类型,它和枚举 ENUM 有点相似,只不过是 SET 能够保存多个值而 ENUM 只能保存一个值而已。而且, SET 类型最多只能够有 64 个预定的值,而 ENUM 类型却能够处理最多 65,535 个预定义的值。而如果需要有大于 64 个值的集合,该怎么办呢,这时就需要定义多个集合来一起解决这个问题了。
4. 用 mysql_unbuffered_query() 开发快速的脚本
这个函数能用来替换 mysql_query() 函数,主要的区别就是 mysql_unbuffered_query() 执行完查询后马上返回,不需要等待或者对数据库加锁。 但是返回的行数不能用mysql_num_rows() 函数来检查,因为输出的结果集大小未知。
5. 通配符
SQL 的通配符有两种:“ * ”和“ % ”。分别用在不同的情况下。例如:如果你想看到数据库的所有内容,可以像这样来查询:
<ol class="dp-c"><li class="alt"><span><span>SELECT * FROM dbname WHERE USER_ID LIKE </span><span class="string">'%'</span><span>; </span></span></li></ol>
这里,两个通配符都被用上了。他们表示相同的意思 ?? 都是用来匹配任何的字符串,但是他们用在不同的上下文中。“ * ”用来匹配字段名,而“ % ”用来匹配字段值。另外一个不容易引起注意的地方是“ % ”通配符需要和 LIKE 关键字一起使用。 还有一个通配符,就是下划线“ _ ”,它代表的意思和上面不同,是用来匹配任何单个的字符的。
6. NOT NULL 和空记录
如果用户在没有填任何东西的情况下按了 submit 按钮,会怎样呢?如果你确实需要一个值,那么可以用客户端脚本或者服务器端脚本来进行数据验证。但是,在数据库中却是允许一些字段被空出来什么也不填。对此类纪录, MySQL 将要为之执行一些事情:插入值 NULL ,即缺省的操作。
如果你在字段定义中为之声明了 NOT NULL (在建立或者修改这个字段的时候), MySQL 将把这个字段空出来什么东西也不填。对于一个 ENUM 枚举类型的字段,如果你为之声明了 NOT NULL , MySQL 将把枚举集的第一个值插入到字段中。也就是说, MySQL 把枚举集的第一个值作为这个枚举类型的缺省值。
一个值为 NULL 的纪录和一个空纪录是有一些区别的。 % 通配符可以匹配空纪录,但是却不能匹配 NULL 纪录。在某些时候,这种区别会造成一些意想不到的后果。就我的经验而言,任何字段都应该声明为 NOT NULL 。这样许多的SELECT 查询语句就能够正常运转了。注意在搜索 NULL 时,必须用“ IS ”关键字,而 LIKE 是不会正常工作的。 在最后要提到的是,如果你在加入或者修改一个新的字段之前,数据库中已经有了一些记录了,这时新加入的字段在原来的纪录中的值,可能是 NULL ,也可能为空。这也算是 MySQL 的一个 Bug 吧,所以在这种情况下,使用 SELECT 查询要特别的小心。

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor