Blogger Information
Blog 175
fans 1
comment 0
visits 385837
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
MySQL 什么时候使用INNER JOIN 或 LEFT JOIN
dxp2tq的博客
Original
1413 people have browsed it

举个例子:
商品表goods
商品图片表goods_img

商品表:
CREATE TABLE goods (
id int,
name varchar(100) COMMENT ‘商品名称’,
img_id int COMMENT ‘图片ID’
);
INSERT INTO goods (id, name, img_id) VALUES
(1, ‘键盘’, 1),
(2, ‘鼠标’, null),
(3, ‘网卡’, 3),
(4, ‘硬盘’, null);

商品图片表:
CREATE TABLE goods_img (
id int,
url varchar(500) COMMENT ‘图片url’
);
INSERT INTO goods_img (id, url) VALUES
(1, ‘upload/20211207/jianpan.jpg’),
(2, ‘upload/20211207/shubiao.jpg’),
(3, ‘upload/20211207/wangka.jpg’),
(4, ‘upload/20211207/yingpan.jpg’);

inner join查询:
SELECT
goods.id,
goods.name,
goods_img.url
FROM
goods inner join goods_img on goods.img_id = goods_img.id

| id | name | url |
| 1 | 键盘 | ‘upload/20211207/jianpan.jpg’|
| 3 | 网卡 | ‘upload/20211207/wangka.jpg’|
这样的结果看起不对,没有列出所有的商品。因为商品的记录有4条,这里只列出了2条。

SELECT
goods.id,
goods.name,
goods_img.url
FROM
goods
LEFT JOIN goods_img ON goods.img_id = goods_img.id

| id | name | url |
| 1 | 键盘 | ‘upload/20211207/jianpan.jpg’ |
| 3 | 网卡 | ‘upload/20211207/wangka.jpg’ |
| 2 | 鼠标 | ‘upload/20211207/shubiao.jpg’ |
| 4 | 硬盘 | ‘upload/20211207/yingpan.jpg’ |

如果单纯看逻辑运算数量,inner join会比left join更优,因为inner join会返回两表的交集,而left join会返回左表的全部记录。并且inner join会默认使用较小的表作为主表进行循环。
但是有时候inner join也会比left join 慢,具体原因需要具体分析,这里举个例子:大表的连接字段没有建索引,小表建索引了,然后left join中左表是大表,在循环查找会使用小表的索引,而inner join会自动使用小表作为主表,然后循环查找大表(无法使用索引),所以就会很慢。

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post