Home Database Mysql Tutorial 关于MySQL应该学习的6件事_MySQL

关于MySQL应该学习的6件事_MySQL

May 27, 2016 pm 01:46 PM
mysql php development

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>
Copy after login

 函数 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>
Copy after login

在指定表名和列名的情况下,只引用列名:

<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>
Copy after login

聚集函数的引用就是引用名:

<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>
Copy after login

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>
Copy after login

集合 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>
Copy after login

这里,两个通配符都被用上了。他们表示相同的意思 ?? 都是用来匹配任何的字符串,但是他们用在不同的上下文中。“ * ”用来匹配字段名,而“ % ”用来匹配字段值。另外一个不容易引起注意的地方是“ % ”通配符需要和 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 查询要特别的小心。

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: The Ease of Data Management for Beginners MySQL: The Ease of Data Management for Beginners Apr 09, 2025 am 12:07 AM

MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

Can I retrieve the database password in Navicat? Can I retrieve the database password in Navicat? Apr 08, 2025 pm 09:51 PM

Navicat itself does not store the database password, and can only retrieve the encrypted password. Solution: 1. Check the password manager; 2. Check Navicat's "Remember Password" function; 3. Reset the database password; 4. Contact the database administrator.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

How to create navicat premium How to create navicat premium Apr 09, 2025 am 07:09 AM

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

How to view database password in Navicat for MariaDB? How to view database password in Navicat for MariaDB? Apr 08, 2025 pm 09:18 PM

Navicat for MariaDB cannot view the database password directly because the password is stored in encrypted form. To ensure the database security, there are three ways to reset your password: reset your password through Navicat and set a complex password. View the configuration file (not recommended, high risk). Use system command line tools (not recommended, you need to be proficient in command line tools).

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

How to create a new connection to mysql in navicat How to create a new connection to mysql in navicat Apr 09, 2025 am 07:21 AM

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

How to execute sql in navicat How to execute sql in navicat Apr 08, 2025 pm 11:42 PM

Steps to perform SQL in Navicat: Connect to the database. Create a SQL Editor window. Write SQL queries or scripts. Click the Run button to execute a query or script. View the results (if the query is executed).

See all articles