Mysql连表查询

在查询表的时候,有时我们需要在多个表中获取信息。这时我们会使用left join、right join或者inner join。

表初始化

这里我们初始化两个表,product和product_detail表。
product:

CREATE TABLE `product` (
     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
     `number` int(10) unsigned DEFAULT NULL,
      PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

insert into product(id,number) values (1,2),(2,2),(3,3);

product_detail:

CREATE TABLE `product_detail` (
  `id` int(10) unsigned NOT NULL,
 `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

insert into product_detail(id,name) values (1,'nihao'),(3,'hello world'),(4,'wo hao');

left join/right join

left join和right join的使用基本是一样的,唯一的区别在于是读取左边的全部数据还是读取右边的全部数据。所以下面我们以left join为例。

示例

执行以下sql命令:

select * from product left join product_detail on product.id = product_detail.id;

输出结果:

id number id name
1 2 1 nihao
2 2 NULL NULL
3 3 3 hello world

由结果可以看出,left join会将product中的结果全部输出,如果右表中有满足条件的则拼接在右边。相反,如果右表没有满足条件的,也依然后输出一行全部为NULL的数据(如第二行)。

on与where的区别

我们先来执行以下sql命令:

select * from product left join product_detail on product.id = product_detail.id where product.id=1;

输出结果:

id number id name
1 2 1 nihao

由结果可以看出:

  • on 条件用于决定如何从右表(product_detail)中检索满足条件的数据行。
  • where子句在on条件的检索过程中不会被执行,仅在检索过程结束后才会执行。where子句的执行是在on子句的检索结果中过滤满足where条件的数据行。

inner join

示例

执行以下sql命令:

select * from product inner join product_detail on product.id = product_detail.id;

输出结果:

id number id name
1 2 1 nihao
3 3 3 hello world

由结果可以看出inner join的输出结果中并没有包含不满足on条件的数据行。

执行以下sql命令:

select * from product,product_detail where product.id = product_detail.id;

输出结果:

id number id name
1 2 1 nihao
3 3 3 hello world

由此可知,该sql命令和inner join的执行是等价的。

猜你喜欢

转载自blog.csdn.net/zhaoruda/article/details/80144285