mysql>select*from a, b where a.id = b.id and a.id =2; +----+-----+----+-----+ | id | var | id | var | +----+-----+----+-----+ |2| C |2| D | +----+-----+----+-----+ 1rowinset (0.00 sec)
mysql>select*from a, b where a.id = b.id and a.id =1; +----+-----+----+-----+ | id | var | id | var | +----+-----+----+-----+ |1| B |1| A | |1| A |1| A | +----+-----+----+-----+ 2rowsinset (0.01 sec)
1.3 无匹配的记录
当根据条件匹配查询无记录时,MySQL不会返回任何记录
1 2
mysql>select*from a, b where a.id = b.id and b.id =3; Emptyset (0.00 sec)
2、左关联left join
语法:
1
xxx leftjoin yyy on
left join以左边表为驱动表(主表),在进行数据匹配时,驱动表的记录只要符合查询条件都会返回,从表的记录如果符合查询条件会拼接到结果集右边,如果没有记录匹配设置字段值为NULL拼接到结果集右边返回到客户端
1 2 3 4 5 6 7 8
mysql>select t1.*, t2.*from a t1 leftjoin b t2 on t1.id = t2.id where t1.id in (2, 4); +----+-----+------+------+ | id | var | id | var | +----+-----+------+------+ |2| C |2| D | |4| F |NULL|NULL| +----+-----+------+------+ 2rowsinset (0.00 sec)
3、右关联 right join
语法格式:
1
xxx rightjoin yyy on
right join和left join原理类似,只是驱动表是右边表,同样的优先匹配驱动表记录,驱动表的记录只要符合查询条件都会返回,从表的记录如果符合查询条件会拼接到结果集左边,如果没有记录匹配设置字段值为NULL拼接到结果集左边返回到客户端
1 2 3 4 5 6 7 8
mysql>select t1.*, t2.*from a t1 rightjoin b t2 on t1.id = t2.id where t2.id in (2, 3); +------+------+----+-----+ | id | var | id | var | +------+------+----+-----+ |2| C |2| D | |NULL|NULL|3| E | +------+------+----+-----+ 2rowsinset (0.00 sec)
mysql>select t1.*from a t1 unionselect t2.*from b t2; +----+-----+ | id | var | +----+-----+ |1| A | |1| B | |2| C | |4| F | |2| D | |3| E | +----+-----+ 6rowsinset (0.01 sec)
查询子句包含where条件:
1 2 3 4 5 6 7 8 9 10 11
mysql>select t1.*from a t1 unionselect t2.*from b t2 where t2.id =1 -> ; +----+-----+ | id | var | +----+-----+ |1| A | |1| B | |2| C | |4| F | +----+-----+ 4rowsinset (0.00 sec)
5、附录
5.1 建表语句
1 2 3 4 5 6 7 8 9
create table a ( id intnot null, val varchar(5) not null );
create table b( id intnot null, val varchar(5) not null );
5.2 初始数据
1 2
insert into a values (1, 'A'), (1, 'B'), (2, 'C'), (4, 'F'); insert into b values (1, 'A'), (2, 'D'), (3, 'E');