两张表:
1 mysql> select * from student; 2 +----+------+------+ 3 | id | name | age | 4 +----+------+------+ 5 | 1 | 小王 | 16 | 6 | 2 | 小红 | 18 | 7 | 3 | 小明 | 20 | 8 | 4 | 小李 | 22 | 9 | 5 | 小强 | 17 | 10 +----+------+------+ 11 5 rows in set (0.00 sec)
1 mysql> select * from mark; 2 +----+------+-----------+ 3 | id | mark | studentid | 4 +----+------+-----------+ 5 | 1 | 61 | 2 | 6 | 2 | 45 | 2 | 7 | 3 | 70 | 3 | 8 +----+------+-----------+ 9 3 rows in set (0.00 sec)
一、内连接(inner join)
1 mysql> select s.name,m.mark from student s,mark m where s.id=m.studentid; 2 +------+------+ 3 | name | mark | 4 +------+------+ 5 | 小红 | 61 | 6 | 小红 | 45 | 7 | 小明 | 70 | 8 +------+------+ 9 3 rows in set (0.07 sec) 10 mysql> select s.name,m.mark from student s inner join mark m on s.id=m.studentid; 11 +------+------+ 12 | name | mark | 13 +------+------+ 14 | 小红 | 61 | 15 | 小红 | 45 | 16 | 小明 | 70 | 17 +------+------+ 18 3 rows in set (0.06 sec)
二、左连接(left join)
1 mysql> select s.name,m.mark from student s left join mark m on s.id=m.studentid; 2 +------+------+ 3 | name | mark | 4 +------+------+ 5 | 小红 | 61 | 6 | 小红 | 45 | 7 | 小明 | 70 | 8 | 小王 | NULL | 9 | 小李 | NULL | 10 | 小强 | NULL | 11 +------+------+ 12 6 rows in set (0.07 sec)
三、右连接(right join)
1 mysql> select s.name,m.mark from student s right join mark m on s.id=m.studentid; 2 +------+------+ 3 | name | mark | 4 +------+------+ 5 | 小红 | 61 | 6 | 小红 | 45 | 7 | 小明 | 70 | 8 +------+------+ 9 3 rows in set (0.00 sec)
时间: 2024-11-10 13:11:02