1.3.4.9 多表查询
我们使用的表 pet 记录了您拥有多少只宠物,如果您想记录一些它们的生活事件,那么您需要新建一个数据表,这个数据表内容的包括:
- 宠物的名字,让您知道事件是发生在哪个宠物身上的;
- 事件发生的日期;
- 事件的描述;
- 事件的分类;
考虑到这些,我们使用 CREATE TABLE 创建新表 event
mysql> CREATE TABLE event (name VARCHAR(20), date DATE,
-> type VARCHAR(15), remark VARCHAR(255));
Query OK, 0 rows affected (0.01 sec)
和 pet 表一样,我们使用 LOAD DATA LOCAL INFILE
导入数据到 envet 表;
name | date | type | remark |
---|---|---|---|
Fluffy | 1995-05-15 | litter | 4 kittens, 3 female, 1 male |
Buffy | 1993-06-23 | litter | 5 puppies, 2 female, 3 male |
Buffy | 1994-06-19 | litter | 3 puppies, 3 female |
Chirpy | 1999-03-21 | vet | needed beak straightened |
Slim | 1997-08-03 | vet | broken rib |
Bowser | 1991-10-12 | kennel | |
Fang | 1991-10-12 | kennel | |
Fang | 1998-08-28 | birthday | Gave him a new chew toy |
Claws | 1998-03-17 | birthday | Gave him a new flea collar |
Whistler | 1998-12-09 | birthday | First birthday |
创建 event.txt,并编辑如下的文本
Fluffy 1995-05-15 litter 4 kittens, 3 female, 1 male
Buffy 1993-06-23 litter 5 puppies, 2 female, 3 male
Buffy 1994-06-19 litter 3 puppies, 3 female
Chirpy 1999-03-21 vet needed beak straightened
Slim 1997-08-03 vet broken rib
Bowser 1991-10-12 kennel
Fang 1991-10-12 kennel
Fang 1998-08-28 birthday Gave him a new chew toy
Claws 1998-03-17 birthday Gave him a new flea collar
Whistler 1998-12-09 birthday First birthday
执行如下语句:
mysql> LOAD DATA LOCAL INFILE '/data/www/mysql/event.txt' INTO table event;
Query OK, 10 rows affected (0.00 sec)
Records: 10 Deleted: 0 Skipped: 0 Warnings: 0
您可以运用之前章节中的知识,检查 event 表中的数据,以及练习一些查询操作;
假如您想知道宠物产仔的年龄情况,查询单个 event 无法满足您的需求,那么您需要用到如下的 2 个表联合查询:
mysql> SELECT pet.name, TIMESTAMPDIFF(YEAR, birth, date) as age, remark
-> FROM pet INNER JOIN event
-> ON pet.name = event.name
-> WHERE 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.00 sec)
从上面的语句中,我们可以得知:
- FROM 的字句中联合了 两个表,因为我们需要从两个表中获取信息;
- 当需要合并表时,两个表之间必需要有相匹配的内容,可以使用关键字 ON 来指定;
- 如果合并的多个表中,出现相同的列名,比方我们的例子中 name ,此时需要列表所在的表,使用 table.column 来表示;
合并的两个表也可以是同一个表
比方说,您想要查询同一种类的宠物,可以进行交配的数据,那么,您可以执行下面的语句:
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.00 sec)
在后续的章节中,我们将会介绍 JOIN 的详细语法。