当前位置: 代码迷 >> MySQL >> MySQL Tutorial(一)
  详细解决方案

MySQL Tutorial(一)

热度:291   发布时间:2016-05-05 16:23:03.0
MySQL Tutorial(1)

MySQL Tutorial

目前的情况是一边学Java,一边学习MySQL。看的是MySQL提供的文档,这篇博文是学习的总结。(2016-4-3)


本文最后更新时间:2016-4-5


NOTE:关于MySQL的安装文档在这里


3.1-连接和断开MySQL服务

1.查看help信息

shell> mysql --help

2.连接到MySQL服务程序

shell> mysql -h host -u user -p

host:运行着MySQL服务的主机名。如果是在你本机上安装了,那-h host这部分可以不写。也即执行mysql -u user -p就可以。如果硬要写,那么host写成localhost,表明MySQL服务运行在本地主机上。比如下面这个登陆的例子。

user:表示你以user这个账户登陆到MySQL服务。MySQL在安装过程中会自动创建root账户,密码为创建过程中你输入的那个密码。如果安装过程没有输入,则root账户密码默认为空。(至少在我的ubuntu机器上是这样的一个情况,windows下如何我不知道。如果你在windos下操作,那可能和这有出路。我的建议是:如果你是计科学生,现在抛弃windos还为时不晚。)

在登陆前,请先确保MySQL服务正在运行。使用sudo service mysql status来查看MySQL的运行状态。比如在我的机器上的查询过程如下:

wallace@zhenghong-E430:~$ sudo service mysql status[sudo] password for wallace:  * MySQL Community Server 5.7.11 is runningwallace@zhenghong-E430:~$ 

使用root账户登陆MySQL,如下:

[email protected]:~$ mysql -h localhost -u root -pEnter password: Welcome to the MySQL monitor.  Commands end with ; or \g.Your MySQL connection id is 2Server version: 5.7.11 MySQL Community Server (GPL)Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> 

3.断开MySQL的连接

mysql> QUIT

3.2-输入查询语句


1:查看MySQL版本和当前数据

mysql> SELECT VERSION(), CURRENT_DATE;+-----------+--------------+| VERSION() | CURRENT_DATE |+-----------+--------------+| 5.7.11    | 2016-04-03   |+-----------+--------------+1 row in set (0.00 sec)mysql> 

2:输入简单的表达式

mysql> SELECT SIN(PI()/4), (4+1)*5    -> ;+--------------------+---------+| SIN(PI()/4)        | (4+1)*5 |+--------------------+---------+| 0.7071067811865475 |      25 |+--------------------+---------+1 row in set (0.04 sec)mysql>

3:在同一行输入多个查询语句(用分号隔开)

mysql> SELECT VERSION(); SELECT NOW();+-----------+| VERSION() |+-----------+| 5.7.11    |+-----------+1 row in set (0.00 sec)+---------------------+| NOW()               |+---------------------+| 2016-04-03 23:09:58 |+---------------------+1 row in set (0.00 sec)mysql> 

4:将一句查询语句写在多行中(因为MySQL判定一条查询语句时看的是分号而不是输入的行数,所以你可以这么干)

mysql> SELECT    -> USER()    -> ,    -> CURRENT_DATE;+----------------+--------------+| USER()         | CURRENT_DATE |+----------------+--------------+| [email protected] | 2016-04-03   |+----------------+--------------+1 row in set (0.04 sec)mysql> 

5:输入“\c”来清空你当前以输入的语句


3.3-创建并使用数据库


1:查看当前已创建了哪些数据库

mysql> SHOW DATABASES;+--------------------+| Database           |+--------------------+| information_schema || mysql              || performance_schema || sys                |+--------------------+4 rows in set (0.09 sec)mysql> 

2:access到已创建好的数据库中(USE和QUIT一样,不需要使用分号来结束语句,所以USE必须写在一行中))

mysql> USE sysReading table information for completion of table and column namesYou can turn off this feature to get a quicker startup with -ADatabase changedmysql> 

1:创建数据库

mysql> CREATE DATABASE test;Query OK, 1 row affected (0.04 sec)mysql>

2:让你创建的test数据库成为current database

mysql> USE testDatabase changedmysql> 

3:如何让你在登陆MySQL服务时就将current database切换到你设置的那个?
答案:在登陆命令的后面加上数据库名就好了,比如下面的例子

shell> mysql -h host -u user -p test

4:查看current database是哪个

mysql> SELECT DATABASE()    -> ;+------------+| DATABASE() |+------------+| test       |+------------+1 row in set (0.00 sec)mysql> 

5:查看current database里的表有哪些

mysql> SHOW TABLES    -> ;Empty set (0.00 sec)mysql>

Empty set表示current database里还没有表


6:建表

mysql> CREATE TABLE pet (    -> name VARCHAR(20),    -> owner VARCHAR(20),    -> species VARCHAR(20),    -> sex CHAR(1),    -> birth DATE,    -> death DATE    -> );Query OK, 0 rows affected (0.92 sec)mysql> 

7:MySQL支持的数据类型
VARCHAR:是CHAR类型,但它尤其适合用在同一个表中的不同记录的同一个属性值长度不一样的情况。比如上表的name属性,它不是定长的。它可以是petty,长度为5;也可以是tom,长度为3。

CHAR:(未完待续)
DATE:(未完待续)


8:更改表

ALTER TABLE

9:查看表的详细信息

mysql> DESCRIBE pet;+---------+-------------+------+-----+---------+-------+| Field   | Type        | Null | Key | Default | Extra |+---------+-------------+------+-----+---------+-------+| name    | varchar(20) | YES  |     | NULL    |       || owner   | varchar(20) | YES  |     | NULL    |       || species | varchar(20) | YES  |     | NULL    |       || sex     | char(1)     | YES  |     | NULL    |       || birth   | date        | YES  |     | NULL    |       || death   | date        | YES  |     | NULL    |       |+---------+-------------+------+-----+---------+-------+6 rows in set (0.03 sec)mysql> 

10:向表中插入数据

  • 从文件中导入数据到表格中

假设home下有一个pet.txt,里面已经输入了记录

mysql> LOAD DATA LOCAL INFILE '/home/wallace/pet.txt' INTO TABLE pet;Query OK, 2 rows affected, 5 warnings (0.06 sec)Records: 2  Deleted: 0  Skipped: 0  Warnings: 5mysql> 
  • 使用INSERT语句插入
mysql> INSERT INTO pet    -> VALUES ('Puffball', 'Diane', 'hamseter', 'f', '1999-03-30', NULL);Query OK, 1 row affected (0.06 sec)mysql> 

11:在表中检索信息

SELECT what_to_selectFROM which_tableWHERE conditions_to_satisfy;
mysql> SELECT * FROM pet;+--------+--------+---------+------+------------+------------+| name   | owner  | species | sex  | birth      | death      |+--------+--------+---------+------+------------+------------+| Fluffy | Harold | cat     | f    | 1993-02-04 | NULL       || Claws  | Gwen   | cat     | m    | 1994-03-17 | NULL       || Buffy  | Harold | dog     | f    | 1989-05-13 | NULL       || Fang   | Benny  | dog     | m    | 1990-08-27 | NULL       || Bowser | Diane  | dog     | m    | 1979-08-31 | 1995-07-29 || Chirpy | Gwen   | bird    | f    | 1996-09-11 | NULL       || Whistl | Gwen   | bird    | NULL | 1997-12-09 | NULL       || Slim   | Benny  | snake   | m    | 1996-04-29 | NULL       || Puff   | Diane  | hamster | f    | 1999-03-30 | NULL       |+--------+--------+---------+------+------------+------------+9 rows in set (0.00 sec)mysql> 

12:如何修改表中的数据项
- (如果你是从文本中导入的数据,而那个文本还存在)修改文本pet.txt到正确的情况。删除表格中的数据,然后再重新LOAD

  • 使用update语句修改
mysql> UPDATE pet SET birth = '1989-08-31' WHERE name = 'Bowser' ;Query OK, 1 row affected (0.05 sec)Rows matched: 1  Changed: 1  Warnings: 0mysql> 

13:选择特定的某些行

mysql> SELECT * FROM pet WHERE name = 'Bowser' ;+--------+-------+---------+------+------------+------------+| name   | owner | species | sex  | birth      | death      |+--------+-------+---------+------+------------+------------+| Bowser | Diane | dog     | m    | 1989-08-31 | 1995-07-29 |+--------+-------+---------+------+------------+------------+1 row in set (0.00 sec)mysql> 
mysql> SELECT * FROM pet WHERE birth >= '1998-1-1' ;+--------+-------+---------+------+------------+-------+| name   | owner | species | sex  | birth      | death |+--------+-------+---------+------+------------+-------+| Chirpy | Gwen  | bird    | f    | 1998-09-11 | NULL  || Puff   | Diane | hamster | f    | 1999-03-30 | NULL  |+--------+-------+---------+------+------------+-------+2 rows in set (0.00 sec)mysql>
mysql> SELECT * FROM pet WHERE species = 'dog' AND sex = 'f' ;+-------+--------+---------+------+------------+-------+| name  | owner  | species | sex  | birth      | death |+-------+--------+---------+------+------------+-------+| Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |+-------+--------+---------+------+------------+-------+1 row in set (0.00 sec)mysql> 
mysql> SELECT * FROM pet WHERE species = 'snake' OR species = 'bird' ;+--------+-------+---------+------+------------+-------+| name   | owner | species | sex  | birth      | death |+--------+-------+---------+------+------------+-------+| Chirpy | Gwen  | bird    | f    | 1998-09-11 | NULL  || Whistl | Gwen  | bird    | NULL | 1997-12-09 | NULL  || Slim   | Benny | snake   | m    | 1996-04-29 | NULL  |+--------+-------+---------+------+------------+-------+3 rows in set (0.00 sec)
mysql> SELECT * FROM pet    -> WHERE (species = 'cat' AND sex = 'm')    -> OR    -> (species = 'dog' AND sex = 'f') ;+-------+--------+---------+------+------------+-------+| name  | owner  | species | sex  | birth      | death |+-------+--------+---------+------+------------+-------+| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  || Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |+-------+--------+---------+------+------------+-------+2 rows in set (0.01 sec)mysql> 

14:选择特定的某些列

mysql> SELECT name, birth FROM pet;+--------+------------+| name   | birth      |+--------+------------+| Fluffy | 1993-02-04 || Claws  | 1994-03-17 || Buffy  | 1989-05-13 || Fang   | 1990-08-27 || Bowser | 1989-08-31 || Chirpy | 1998-09-11 || Whistl | 1997-12-09 || Slim   | 1996-04-29 || Puff   | 1999-03-30 |+--------+------------+9 rows in set (0.00 sec)mysql> 
mysql> SELECT owner FROM pet;+--------+| owner  |+--------+| Harold || Gwen   || Harold || Benny  || Diane  || Gwen   || Gwen   || Benny  || Diane  |+--------+9 rows in set (0.04 sec)mysql> 

15:去掉重复记录

mysql> SELECT DISTINCT owner FROM pet;+--------+| owner  |+--------+| Harold || Gwen   || Benny  || Diane  |+--------+4 rows in set (0.02 sec)mysql> 
mysql> SELECT name, species, birth FROM    -> pet    -> WHERE species = 'dog' OR     -> species = 'cat' ;+--------+---------+------------+| name   | species | birth      |+--------+---------+------------+| Fluffy | cat     | 1993-02-04 || Claws  | cat     | 1994-03-17 || Buffy  | dog     | 1989-05-13 || Fang   | dog     | 1990-08-27 || Bowser | dog     | 1989-08-31 |+--------+---------+------------+5 rows in set (0.01 sec)mysql> 

16:对输出结果对行进行排序(DESC表示降序排列,MySQL默认是升序排列的)

mysql> SELECT name, birth FROM pet ORDER BY birth;+--------+------------+| name   | birth      |+--------+------------+| Buffy  | 1989-05-13 || Bowser | 1989-08-31 || Fang   | 1990-08-27 || Fluffy | 1993-02-04 || Claws  | 1994-03-17 || Slim   | 1996-04-29 || Whistl | 1997-12-09 || Chirpy | 1998-09-11 || Puff   | 1999-03-30 |+--------+------------+9 rows in set (0.02 sec)mysql> 
mysql> SELECT name, birth FROM pet ORDER BY birth DESC;+--------+------------+| name   | birth      |+--------+------------+| Puff   | 1999-03-30 || Chirpy | 1998-09-11 || Whistl | 1997-12-09 || Slim   | 1996-04-29 || Claws  | 1994-03-17 || Fluffy | 1993-02-04 || Fang   | 1990-08-27 || Bowser | 1989-08-31 || Buffy  | 1989-05-13 |+--------+------------+9 rows in set (0.00 sec)mysql> 

按照species升序排列,birth降序排列的顺序来排列

mysql> mysql> SELECT name, species, birth FROM pet ORDER BY species, birth DESC;+--------+---------+------------+| name   | species | birth      |+--------+---------+------------+| Chirpy | bird    | 1998-09-11 || Whistl | bird    | 1997-12-09 || Claws  | cat     | 1994-03-17 || Fluffy | cat     | 1993-02-04 || Fang   | dog     | 1990-08-27 || Bowser | dog     | 1989-08-31 || Buffy  | dog     | 1989-05-13 || Puff   | hamster | 1999-03-30 || Slim   | snake   | 1996-04-29 |+--------+---------+------------+9 rows in set (0.00 sec)mysql> 

17:日期计算

mysql> SELECT name, birth, CURDATE(),    -> TIMESTAMPDIFF(YEAR, birth, CURDATE()) AS age    -> FROM pet;+--------+------------+------------+------+| name   | birth      | CURDATE()  | age  |+--------+------------+------------+------+| Fluffy | 1993-02-04 | 2016-04-04 |   23 || Claws  | 1994-03-17 | 2016-04-04 |   22 || Buffy  | 1989-05-13 | 2016-04-04 |   26 || Fang   | 1990-08-27 | 2016-04-04 |   25 || Bowser | 1989-08-31 | 2016-04-04 |   26 || Chirpy | 1998-09-11 | 2016-04-04 |   17 || Whistl | 1997-12-09 | 2016-04-04 |   18 || Slim   | 1996-04-29 | 2016-04-04 |   19 || Puff   | 1999-03-30 | 2016-04-04 |   17 |+--------+------------+------------+------+9 rows in set (0.01 sec)mysql> 
mysql> SELECT name, birth, CURDATE(),    -> TIMESTAMPDIFF(YEAR, birth, CURDATE()) AS age    -> FROM pet ORDER BY name;+--------+------------+------------+------+| name   | birth      | CURDATE()  | age  |+--------+------------+------------+------+| Bowser | 1989-08-31 | 2016-04-04 |   26 || Buffy  | 1989-05-13 | 2016-04-04 |   26 || Chirpy | 1998-09-11 | 2016-04-04 |   17 || Claws  | 1994-03-17 | 2016-04-04 |   22 || Fang   | 1990-08-27 | 2016-04-04 |   25 || Fluffy | 1993-02-04 | 2016-04-04 |   23 || Puff   | 1999-03-30 | 2016-04-04 |   17 || Slim   | 1996-04-29 | 2016-04-04 |   19 || Whistl | 1997-12-09 | 2016-04-04 |   18 |+--------+------------+------------+------+9 rows in set (0.00 sec)mysql> 
mysql> SELECT name, birth, CURDATE(), TIMESTAMPDIFF(YEAR, birth, CURDATE()) AS age FROM pet ORDER BY age DESC;+--------+------------+------------+------+| name   | birth      | CURDATE()  | age  |+--------+------------+------------+------+| Buffy  | 1989-05-13 | 2016-04-04 |   26 || Bowser | 1989-08-31 | 2016-04-04 |   26 || Fang   | 1990-08-27 | 2016-04-04 |   25 || Fluffy | 1993-02-04 | 2016-04-04 |   23 || Claws  | 1994-03-17 | 2016-04-04 |   22 || Slim   | 1996-04-29 | 2016-04-04 |   19 || Whistl | 1997-12-09 | 2016-04-04 |   18 || Chirpy | 1998-09-11 | 2016-04-04 |   17 || Puff   | 1999-03-30 | 2016-04-04 |   17 |+--------+------------+------------+------+9 rows in set (0.00 sec)mysql> 

数据不为空的写法

mysql> SELECT name, birth, death, TIMESTAMPDIFF(YEAR, birth, death) AS age FROM pet WHERE death IS NOT NULL ORDER BY age;+--------+------------+------------+------+| name   | birth      | death      | age  |+--------+------------+------------+------+| Bowser | 1989-08-31 | 1995-07-29 |    5 |+--------+------------+------------+------+1 row in set (0.00 sec)mysql> 

MySQL提供的日期函数:YEAR(), MONTH(), DAYOFMONTH()
这个例子应该可以让你明白它们的含义

mysql> SELECT name, birth, YEAR(birth), MONTH(birth), DAYOFMONTH(birth) FROM pet;+--------+------------+-------------+--------------+-------------------+| name   | birth      | YEAR(birth) | MONTH(birth) | DAYOFMONTH(birth) |+--------+------------+-------------+--------------+-------------------+| Fluffy | 1993-02-04 |        1993 |            2 |                 4 || Claws  | 1994-03-17 |        1994 |            3 |                17 || Buffy  | 1989-05-13 |        1989 |            5 |                13 || Fang   | 1990-08-27 |        1990 |            8 |                27 || Bowser | 1989-08-31 |        1989 |            8 |                31 || Chirpy | 1998-09-11 |        1998 |            9 |                11 || Whistl | 1997-12-09 |        1997 |           12 |                 9 || Slim   | 1996-04-29 |        1996 |            4 |                29 || Puff   | 1999-03-30 |        1999 |            3 |                30 |+--------+------------+-------------+--------------+-------------------+9 rows in set (0.00 sec)mysql> 

查找5月份出生的狗狗

mysql> SELECT name, birth FROM pet WHERE MONTH(birth) = '5';+-------+------------+| name  | birth      |+-------+------------+| Buffy | 1989-05-13 |+-------+------------+1 row in set (0.00 sec)mysql> 
mysql> SELECT name, birth FROM pet    -> WHERE MONTH(birth) = MONTH(DATE_ADD(CURDATE(), INTERVAL 1 MONTH));+-------+------------+| name  | birth      |+-------+------------+| Buffy | 1989-05-13 |+-------+------------+1 row in set (0.00 sec)mysql> 

再来一个例子,你就明白了

mysql> SELECT name, birth FROM pet WHERE MONTH(birth) = MONTH(DATE_ADD(CURDATE(), INTERVAL 30 DAY));+-------+------------+| name  | birth      |+-------+------------+| Buffy | 1989-05-13 |+-------+------------+1 row in set (0.00 sec)mysql> 

MOD函数

mysql> SELECT name, birth FROM pet WHERE MONTH(birth) = MOD(MONTH(CURDATE()), 12) + 1;+-------+------------+| name  | birth      |+-------+------------+| Buffy | 1989-05-13 |+-------+------------+1 row in set (0.00 sec)mysql> 

18:数据为空如何操作

mysql> SELECT 1 IS NULL, 1 IS NOT NULL;+-----------+---------------+| 1 IS NULL | 1 IS NOT NULL |+-----------+---------------+|         0 |             1 |+-----------+---------------+1 row in set (0.00 sec)mysql> 

记住一句话:When doing an ORDER BY, NULL values are presented first if you do ORDER BY … ASC and last if you do ORDER BY … DESC.

In MySQL, 0 or NULL means false and anything else means true


19:模式匹配
记住下面五点:
1:_(下划线)代表一个任一字符。%(百分号)代表任意个字符

2:相等和不想等用LIKE和NOT LIKE表示

3:模式匹配是大小写不敏感的

4:使用REGEXP(或者RLIKE)和NOT REGEXP(或者NOT RLIKE)来连接正则表达式。

5:几个扩展的正则表达式用法
- “.”(点号)匹配单个字符

  • […]匹配在方括号内的任何一个字符。比如,[abc]匹配“a”,“b”或“c“

  • 怎样匹配某个范围内的字符呢?答案:[a-z]匹配所有的字母;[0-9]匹配所有的数字

  • “匹配任意个写在它前面的字符(包括0个)。比如”x“匹配任意长度的只含x的字符串;[0-9]匹配任意长度的数字串;”.*“匹配任意字符串

  • 英文原句:To anchor a pattern so that it must match the beginning or end of the value being tested, use “^” at the beginning or “$” at the end of the pattern.

例如:To find names beginning with “b”, use “^” to match the beginning of the name:

mysql> SELECT * FROM pet     -> WHERE name LIKE 'b%' ;+--------+--------+---------+------+------------+------------+| name   | owner  | species | sex  | birth      | death      |+--------+--------+---------+------+------------+------------+| Buffy  | Harold | dog     | f    | 1989-05-13 | NULL       || Bowser | Diane  | dog     | m    | 1989-08-31 | 1995-07-29 |+--------+--------+---------+------+------------+------------+2 rows in set (0.00 sec)mysql> 

例如:To find names ending with “fy”, use “$” to match the end of the name:

mysql> SELECT * FROM pet WHERE name REGEXP 'fy$';+--------+--------+---------+------+------------+-------+| name   | owner  | species | sex  | birth      | death |+--------+--------+---------+------+------------+-------+| Fluffy | Harold | cat     | f    | 1993-02-04 | NULL  || Buffy  | Harold | dog     | f    | 1989-05-13 | NULL  |+--------+--------+---------+------+------------+-------+2 rows in set (0.00 sec)mysql> 

例如:To find names containing a “w”, use this query:

mysql> SELECT * FROM pet WHERE name REGEXP 'w';+--------+-------+---------+------+------------+------------+| name   | owner | species | sex  | birth      | death      |+--------+-------+---------+------+------------+------------+| Claws  | Gwen  | cat     | m    | 1994-03-17 | NULL       || Bowser | Diane | dog     | m    | 1989-08-31 | 1995-07-29 || Whistl | Gwen  | bird    | NULL | 1997-12-09 | NULL       |+--------+-------+---------+------+------------+------------+3 rows in set (0.00 sec)mysql> 

例如:To find names containing exactly five characters, use “^” and “$” to match the beginning and end of the name, and five instances of “.” in between:

mysql> SELECT * FROM pet WHERE name REGEXP '^.....$' ;+-------+--------+---------+------+------------+-------+| name  | owner  | species | sex  | birth      | death |+-------+--------+---------+------+------------+-------+| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  || Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |+-------+--------+---------+------+------------+-------+2 rows in set (0.00 sec)mysql> 

NOTE:你可以在正则表达式中使用{n}来重复写在它前面的字符n次。比如,你可以这样完成上面的例子

mysql> SELECT * FROM pet WHERE name REGEXP '^.{5}$' ;+-------+--------+---------+------+------------+-------+| name  | owner  | species | sex  | birth      | death |+-------+--------+---------+------+------------+-------+| Claws | Gwen   | cat     | m    | 1994-03-17 | NULL  || Buffy | Harold | dog     | f    | 1989-05-13 | NULL  |+-------+--------+---------+------+------------+-------+2 rows in set (0.00 sec)mysql> 

19:统计行数

mysql> SELECT COUNT(*) FROM pet;+----------+| COUNT(*) |+----------+|        9 |+----------+1 row in set (0.01 sec)mysql> 

20:GROUP BY语句

mysql> SELECT owner, COUNT(*) FROM pet GROUP BY owner;+--------+----------+| owner  | COUNT(*) |+--------+----------+| Benny  |        2 || Diane  |        2 || Gwen   |        3 || Harold |        2 |+--------+----------+4 rows in set (0.02 sec)mysql> 

有没有发现什么?
如果你要统计的属性是主键的话(因为主键是唯一的),那也就没必要统计了,肯定只有一条。但如果你要统计的属性不是主键,那意味着可能有多条属性值是一样的记录。比如你要统计A属性,你就SELECT A,然后再GROUP BY A一下就行了。看看人家英文原文是怎么表达的:The preceding query uses GROUP BY to group all records for each owner.

mysql> SELECT species, COUNT(*) FROM pet GROUP BY species;+---------+----------+| species | COUNT(*) |+---------+----------+| bird    |        2 || cat     |        2 || dog     |        3 || hamster |        1 || snake   |        1 |+---------+----------+5 rows in set (0.01 sec)mysql> 
mysql> SELECT sex, COUNT(*) FROM pet GROUP BY sex;+------+----------+| sex  | COUNT(*) |+------+----------+| NULL |        1 || f    |        4 || m    |        4 |+------+----------+3 rows in set (0.00 sec)mysql> 

注意下面这个GROUP BY 2个属性的

mysql> SELECT species, sex, COUNT(*) FROM pet GROUP BY species, sex;+---------+------+----------+| species | sex  | COUNT(*) |+---------+------+----------+| bird    | NULL |        1 || bird    | f    |        1 || cat     | f    |        1 || cat     | m    |        1 || dog     | f    |        1 || dog     | m    |        2 || hamster | f    |        1 || snake   | m    |        1 |+---------+------+----------+8 rows in set (0.00 sec)mysql> 

一个更加复杂的例子

mysql> SELECT species, sex, COUNT(*) FROM pet WHERE species = 'dog' OR species = 'cat' GROUP BY species, sex;+---------+------+----------+| species | sex  | COUNT(*) |+---------+------+----------+| cat     | f    |        1 || cat     | m    |        1 || dog     | f    |        1 || dog     | m    |        2 |+---------+------+----------+4 rows in set (0.00 sec)mysql> 
mysql> SELECT species, sex, COUNT(*) FROM pet    -> WHERE sex IS NOT NULL    -> GROUP BY species, sex;+---------+------+----------+| species | sex  | COUNT(*) |+---------+------+----------+| bird    | f    |        1 || cat     | f    |        1 || cat     | m    |        1 || dog     | f    |        1 || dog     | m    |        2 || hamster | f    |        1 || snake   | m    |        1 |+---------+------+----------+7 rows in set (0.00 sec)mysql> 

接下来是几个比较难的查询,涉及到了在多个表中进行查询的情况


21:如何同时在两个表中SELECT

mysql> SELECT pet.name,    -> (YEAR(date)-YEAR(birth)) - (RIGHT(date, 5)<RIGHT(birth, 5)) AS age,    -> remark    -> FROM pet INNER JOIN event    -> ON pet.name = event.name    -> WHERE event.type = 'litter' ;+--------+------+-----------------------------+| name   | age  | remark                      |+--------+------+-----------------------------+| Fluffy |    2 | 4 kittens, 3 female, 1 male || Buffy  |    4 | 5 puppies, 2 female, 3 male || Buffy  |    5 | 3 puppies, 3 female         |+--------+------+-----------------------------+3 rows in set (0.03 sec)mysql> 

关于上面这个查询语句,有以下需要注意的地方:
There are several things to note about this query:
? The FROM clause joins two tables because the query needs to pull information from both of them.
? When combining (joining) information from multiple tables, you need to specify how records in one table can be matched to records in the other. This is easy because they both have a name column. The query uses an ON clause to match up records in the two tables based on the name values. The query uses an INNER JOIN to combine the tables. An INNER JOIN permits rows from either table to appear in the result if and only if both tables meet the conditions specified in the ON clause.
In this example, the ON clause specifies that the name column in the pet table must match the name
column in the event table. If a name appears in one table but not the other, the row will not appear
in the result because the condition in the ON clause fails.
? Because the name column occurs in both tables, you must be specific about which table you mean
when referring to the column. This is done by prepending the table name to the column name.

下面是一个表格自己和自己相连的情况

mysql> SELECT p1.name, p1.sex, p2.name, p2.sex, p1.species    -> FROM pet AS p1 INNER JOIN pet AS p2    -> ON p1.species = p2.species AND p1.sex = 'f'     -> AND p2.sex = 'm' ;+--------+------+--------+------+---------+| name   | sex  | name   | sex  | species |+--------+------+--------+------+---------+| Fluffy | f    | Claws  | m    | cat     || Buffy  | f    | Fang   | m    | dog     || Buffy  | f    | Bowser | m    | dog     |+--------+------+--------+------+---------+3 rows in set (0.35 sec)mysql> 

这个例子其实就是配对——从这9只狗中挑出那些可以进行繁殖的那些狗狗。

具体的做法你可以想象成两个相同的pet表进行两层的for循环。也就是从第一个pet表中的第一个狗狗Fluffy开始依次和另一个相同的pet表中的从第一个到最后一个进行判定,看它们这两个狗狗是否满足这两个条件:1,这两个狗的品种相同;2,第一个表中的狗也即是前面的那只狗的sex是f,并且后面一只狗的sex为m。如果满足这两个条件,则配对成功,它们将会在结果中出现,否则不出现。


3.4-获取数据库和数据库中的表格的信息


1:查看当前正在被操作的数据库是哪个?也就是查看current database是哪个

mysql> SELECT DATABASE();+------------+| DATABASE() |+------------+| test       |+------------+1 row in set (0.05 sec)mysql> 

2:查看current database里有哪些表格

mysql> SHOW TABLES;+----------------+| Tables_in_test |+----------------+| event          || pet            |+----------------+2 rows in set (0.00 sec)mysql> 

3:查看某个表格的结构是怎样的?

mysql> DESCRIBE pet;+---------+-------------+------+-----+---------+-------+| Field   | Type        | Null | Key | Default | Extra |+---------+-------------+------+-----+---------+-------+| name    | varchar(20) | YES  |     | NULL    |       || owner   | varchar(20) | YES  |     | NULL    |       || species | varchar(20) | YES  |     | NULL    |       || sex     | char(1)     | YES  |     | NULL    |       || birth   | date        | YES  |     | NULL    |       || death   | date        | YES  |     | NULL    |       |+---------+-------------+------+-----+---------+-------+6 rows in set (0.00 sec)mysql> 

到这里已经走完了MySQL文档中第3章Tutorial的大部分的内容了。剩下的3.5, 3.6, 3.7明天再来吧。深夜了都。

  相关解决方案