码迷,mamicode.com
首页 > 数据库 > 详细

MySQL连接查询

时间:2015-01-19 09:21:16      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

连接查询

1、内链接查询

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

假设有如下两张表studentteacher

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 | 赵六 |

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




技术分享

MySQL连接查询

标签:

原文地址:http://blog.csdn.net/yaguanzhou2014/article/details/42842623

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!