MySQL连接查询

2015-01-21 11:11:42 · 作者: · 浏览: 10

连接查询

1、内链接查询

内连接INNER JOIN使用比较运算符进行表间某些列数据的比较操作,并列出这些表中与连接条件相匹配的数据行组合成新的记录。

假设有如下两张表student,teacher

mysql> select * from student;

+----+------+-----+-------+------+---------+

| id | name | sex | class | math | english |

+----+------+-----+-------+------+---------+

| 1 | 张三 | 男 | 班级1 | 90 | 91 |

| 2 | 李四 | 男 | 班级2 | 88 | 86 |

| 3 | 王五 | 女 | 班级3 | 92 | 88 |

| 4 | 赵六 | 女 | 班级1 | 79 | 80 |

| 5 | 孙七 | 女 | 班级2 | 91 | 96 |

| 6 | 李八 | 男 | 班级3 | 90 | 89 |

+----+------+-----+-------+------+---------+

?

?

mysql> select * from teacher;

+----+--------+-------+

| id | name | class |

+----+--------+-------+

| 1 | 张老师 | 班级1 |

| 2 | 李老师 | 班级2 |

| 3 | 王老师 | 班级3 |

+----+--------+-------+

?

mysql> select student.name,student.class,teacher.name from student,teacher where student.class = teacher.class;

+------+-------+--------+

| name | class | name |

+------+-------+--------+

| 张三 | 班级1 | 张老师 |

| 李四 | 班级2 | 李老师 |

| 王五 | 班级3 | 王老师 |

| 赵六 | 班级1 | 张老师 |

| 孙七 | 班级2 | 李老师 |

| 李八 | 班级3 | 王老师 |

+------+-------+--------+

?

使用内链接查询的方式为:

mysql> select student.name,student.class,teacher.name from student inner join teacher on student.class = teacher.class;

+------+-------+--------+

| name | class | name |

+------+-------+--------+

| 张三 | 班级1 | 张老师 |

| 李四 | 班级2 | 李老师 |

| 王五 | 班级3 | 王老师 |

| 赵六 | 班级1 | 张老师 |

| 孙七 | 班级2 | 李老师 |

| 李八 | 班级3 | 王老师 |

+------+-------+--------+

?

在一个连接查询中,如果涉及到的两个表都是同一个表,这种查询称为字连接查询。字连接查询是一种特殊的内链接,他是指相互连接的表在物理上为同一张表,但可以在逻辑上分为两张表

mysql> select distinct s1.id,s1.name from student as s1,student as s2 where s1.class = s2.class and s2.class = '班级1';

+----+------+

| id | name |

+----+------+

| 1 | 张三 |

| 4 | 赵六 |

+----+------+

?