CREATE DATABASE lxw; use lxw; create table A( id int not null auto_increment, name varchar(8), age int, primary key(id)); insert into A(name, age) values('lxw', 28); insert into A(name, age) values('lxw', 30); insert into A(name, age) values('wxl', 31); insert into A(name, age) values('jzn', 32);
create table B( id int not null auto_increment, name varchar(8), sex varchar(8), primary key(id)); insert into B(name, sex) values('lxw', "M"); insert into B(name, sex) values('wxl', "M"); insert into B(name, sex) values('wxl', "F"); insert into B(name, sex) values('gcm', "F"); mysql> insert into B(name, sex) values('gcm', "F"); Query OK, 1 row affected (0.08 sec)
mysql> select * from A; +----+------+------+ | id | name | age | +----+------+------+ | 1 | lxw | 28 | | 2 | wxl | 31 | | 3 | lxw | 30 | | 4 | jzn | 32 | +----+------+------+ 4 rows in set (0.00 sec)
mysql> select * from B; +----+------+------+ | id | name | sex | +----+------+------+ | 1 | lxw | M | | 2 | wxl | M | | 3 | wxl | F | | 4 | gcm | F | +----+------+------+ 4 rows in set (0.00 sec)
mysql> SELECT * FROM A JOIN B on A.name = B.name; +----+------+------+----+------+------+ | id | name | age | id | name | sex | +----+------+------+----+------+------+ | 1 | lxw | 28 | 1 | lxw | M | | 3 | lxw | 30 | 1 | lxw | M | | 2 | wxl | 31 | 2 | wxl | M | | 2 | wxl | 31 | 3 | wxl | F | +----+------+------+----+------+------+ 4 rows in set (0.00 sec)
mysql> select * from A left join B on A.name=B.name; +----+------+------+------+------+------+ | id | name | age | id | name | sex | +----+------+------+------+------+------+ | 1 | lxw | 28 | 1 | lxw | M | | 3 | lxw | 30 | 1 | lxw | M | | 2 | wxl | 31 | 2 | wxl | M | | 2 | wxl | 31 | 3 | wxl | F | | 4 | jzn | 32 | NULL | NULL | NULL | +----+------+------+------+------+------+ 5 rows in set (0.00 sec)
mysql> select * from A right join B on A.name=B.name; +------+------+------+----+------+------+ | id | name | age | id | name | sex | +------+------+------+----+------+------+ | 1 | lxw | 28 | 1 | lxw | M | | 2 | wxl | 31 | 2 | wxl | M | | 2 | wxl | 31 | 3 | wxl | F | | 3 | lxw | 30 | 1 | lxw | M | | NULL | NULL | NULL | 4 | gcm | F | +------+------+------+----+------+------+ 5 rows in set (0.00 sec)