
7.数据库切换
当存在多个数据库时,可以用下面的命令定义用户想使用的数据库:
use database_name
8.统计函数
SQL有一些统计函数,它们对于生成数据表格很有帮助。下面介绍几个常用的统计函数:
sum (exepression) 计算表达式的和
avg (exepression) 计算表达式的平均值
count (exepression) 对表达式进行简单的计数
count (*) 统计记录数
max (exepression) 求最大值
min (exepression) 求最小值
其中exepression为任何有效的SQL表达式,它可以是一个或多个记录,也可以是别的SQL函数的组合。
二、MySQL使用导引
1.运用MySQL建立新数据库
在shell下运行:
$>mysqladmin create database01
Database "database01" created.
2.启动MySQL
在shell下运行:
$>mysql
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 22 to server version: 3.21. 29a-gamma-debug
无效 'help' for help.
3.更换数据库
mysql>use database01
database changed.
4.创建表
mysql>create table table01 (field01 integer, field02 char(10));
Query OK, 0 rows affected (0.00 sec)
5.列出表清单
mysql>show tables;
Tables in database01
Table01
table02
6.列出表中的字段清单
mysql>show columns from table01;
Field 无效 Null Key Default Extra
field01 int(11) YES
field02 char(10) YES
7.表的数据填写
插入数据
mysql>insert into table01 (field01, field02) values (1, 'first');
Query OK, 1 row affected (0.00 sec)
8.字段的增加
...一次一个字段
mysql>alter table table01 add column field03 char(20);
Query OK, l row affected (0.04 sec)
Records: 1 Duplicates: 0 Warnings: 0
...一次多个字段
mysql>alter table table01 add column field04 date, add column field05 time;
Query OK, l row affected (0.04 sec)
Records: 1 Duplicates: 0 Warnings: 0
注意:每一列都必须以"add column"重新开始。
它运行了吗?让我们看看。
mysql>select * from table01;
field01 field02 field03 field04 field05
1 first NULL NULL NULL
9.多行命令输入
MySQL命令行界面允许把陈述作为一行输入,也可以把它展开为多行输入。这两者之间并没有语法上的区别。使用多行输入,你可以将SQL陈述一步步分解,从而使你更容易理解。
在多行方式下,注释器把每一行都添加到前面的行后,直到你用分号";"来结束这个SQL陈述。一旦键入分号并按回车键,这个陈述即被执行。
下面的例子是同一个严格的SQL陈述的两种输入方法:
单行输入
Mysql>create table table33 (field01 integer, field02 char(30));
多行输入
Mysql>create table table33
->(field01
->integer,
->field02
->char(30));
注意不能将单词断开,如:
正确
mysql>create table table33
->( field01
->integer,
->field02
->char(30));
错误
mysql>create table table33
->( field01 inte
->ger,
->field02
->char(30));
当插入或更改数据时,不能将字段的字符串展开到多行里,否则硬回车将被储存到数据中:
标准操作
mysql>insert into table33 (field02)
->values
->('who thought of foo?');
硬回车储存到数据中
mysql>insert into table33 (field02)
->values
->('who thought
->of foo?');
结果如下:
mysql>select * from table33;
field01 field02
NULL who thought of foo?
NULL who thought
Of foo?
10.表的数据嵌入
mysql>insert into table01 (field01, field02, field03, field04, field05) values
->(2, 'second', 'another', '1999-10-23', '10:30:00');
Query OK, 1 row affected (0.00 sec)
标准日期格式是"yyyy-mm-dd"。
标准时间格式是"hh:mm:ss"。
引号内要求所给的是上述的标准日期和时间格式。
日期也可以"yyyymmdd"形式,时间也可以"hhmmss"形式输入,但其值不需要再加引号。
数字值不需要加引号。这种保存与数据类型无关,这些数据类型都有格式化的专栏来包含(例如:文本,日期,时间,整数等)。
MySQL有一个很有用的命令缓冲区。它保存着你目前已经键入的SQL语句利用它,对于相同的命令,你就不必一遍又一遍地重复输入。下一步我们就来看这样的一个例子。
利用命令缓冲区(及任意的日期和时间格式)增加另一个数据
按两次键盘上的向上箭头键。
回车。
在圆括号内输入新的值,并以分号结尾。
(3, 'a third', 'more', 19991024, 103004);
回车。
新值存在里面了吗?
mysql>select * from table01;
field01 field02 field03 field04 field05
1 first NULL NULL NULL
2 second another 1999-10-23 10:30:00
3 a third more 1999-10-24 10:30:04
