表连接操作
在一张表中读取数据,这是相对简单的,但是在真正的应用中经常需要从多个数据表中读取数据
使用 MySQL 的 JOIN 在两个或多个表中查询数据
- INNER JOIN(内连接,或等值连接):获取两个表中字段匹配关系的记录。
- LEFT JOIN(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
- RIGHT JOIN(右连接):与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。
其中 INNER JOIN(也可以省略 INNER 使用 JOIN,效果一样)
创建示例表
我们先创建两张表 一张是person 一张是student
student 肯定是属于person 但是student 不一样属于person
create table person
(
id int primary key auto_increment,
name varchar(20) not null
);
create table student
(
id int primary key auto_increment,
personid int not null,
number varchar(10)
);Code language: JavaScript (javascript)
插入记录
往person和student里面插入一些记录
mysql> insert into person(name) values
-> ('张飞'),('关羽'),('刘备'),('董卓')
-> ;
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select * from person;
+----+------+
| id | name |
+----+------+
| 1 | 张飞 |
| 2 | 关羽 |
| 3 | 刘备 |
| 4 | 董卓 |
+----+------+
4 rows in set (0.00 sec)
mysql> insert into student(personid,number) values
-> (1,'001'),(2,'002'),(3,'003')
-> ;
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from student;
+----+----------+--------+
| id | personid | number |
+----+----------+--------+
| 1 | 1 | 001 |
| 2 | 2 | 002 |
| 3 | 3 | 003 |
+----+----------+--------+
3 rows in set (0.00 sec)Code language: JavaScript (javascript)
INNER JOIN(等值连接)
select * from person p
inner join student s
on
p.id = s.personid;Code language: JavaScript (javascript)
说白了 就是符合 p.id = s.personid
两张表的公共部分
LEFT JOIN
MySQL left join 与 join 有所不同。 MySQL LEFT JOIN 会读取左边数据表的全部数据(可能重复),即便右边表无对应数据。
select * from person p
left join student s
on
p.id = s.personid;Code language: JavaScript (javascript)
上面语句 就是p表为主 必须全部出现 然后s表可能为空
重复的情况
insert into student(personid,number) values(2,'004');Code language: JavaScript (javascript)
现在有一个学生 它的学号是004 但是他的personid用了关羽的personid
RIGHT JOIN
MySQL RIGHT JOIN 会读取右边数据表的全部数据,即便左边表无对应数据。
select * from person p
right join student s
on
p.id = s.personid;Code language: JavaScript (javascript)
Previous: 排序和分组
Next: NULL 值和正则表达式