21,892
社区成员
发帖
与我相关
我的任务
分享
SELECT a.`goods_id` , a.`goods_name` , b.brand_name
FROM `ecs_goods` AS a
LEFT JOIN ecs_brand AS b ON a.`brand_id` = b.`brand_id`
SELECT a.`goods_id` , a.`goods_name` , b.brand_name
FROM `ecs_goods` AS a, ecs_brand AS b
WHERE a.`brand_id` = b.`brand_id`
SELECT a.`goods_id` , a.`goods_name` , b.brand_name
FROM `ecs_goods` AS a, ecs_brand AS b
WHERE a.`brand_id` = b.`brand_id`
和
SELECT a.`goods_id` , a.`goods_name` , b.brand_name
FROM `ecs_goods` AS a INNER JOIN ecs_brand AS b ON a.`brand_id` = b.`brand_id`
是等效的
SELECT a.`goods_id` , a.`goods_name` , b.brand_name
FROM `ecs_goods` AS a LEFT JOIN ecs_brand AS b ON a.`brand_id` = b.`brand_id`
WHERE b.`field_name`= 123
会被 mysql 优化为
SELECT a.`goods_id` , a.`goods_name` , b.brand_name
FROM `ecs_goods` AS a, ecs_brand AS b
WHERE a.`brand_id` = b.`brand_id`AND b.`field_name`= 123
SELECT a.`goods_id` , a.`goods_name` , b.brand_name
FROM `ecs_goods` AS a, ecs_brand AS b
WHERE a.`brand_id` = b.`brand_id`
和
SELECT a.`goods_id` , a.`goods_name` , b.brand_name
FROM `ecs_goods` AS a
JOIN ecs_brand AS b ON a.`brand_id` = b.`brand_id`
两句sql是完全一样的 mysql会将第一条sql优化成第二条。
第二点:
“在商品表中查品牌商品 和 在品牌表中查商品”
就是说
SELECT a.`goods_id` , a.`goods_name` , b.brand_name
FROM `ecs_goods` AS a
JOIN ecs_brand AS b ON a.`brand_id` = b.`brand_id`
和
SELECT a.`goods_id` , a.`goods_name` , b.brand_name
FROM ecs_brand AS b
JOIN `ecs_goods` AS a ON b.`brand_id`=a.`brand_id`
两句sql的效率是不一样的。
//////////////////////////////////////////////////////////////
以上两点描述正确吗 ?我有没理解错你的意思呢。
如果没有 那第二点大家处理方式都是笛卡尔积。
我的理解是 如果是 ecs_goods` AS a JOIN ecs_brand AS b
那就是商品表的一条记录 扫描品牌表的所有记录。如果有10个商品 10个品牌
那就是10*10=100 扫描了100次
反过来ecs_brand AS b JOIN `ecs_goods` AS a
一个品牌扫描10个商品 那扫描次数也是100次。 那为什么它们的效率不一样呢
--
-- 表的结构 `good_tbl`
--
CREATE TABLE `good_tbl` (
`good_id` int(10) unsigned NOT NULL auto_increment,
`brand_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`good_id`)
) ENGINE=MyISAM DEFAULT CHARSET=gbk AUTO_INCREMENT=4 ;
--
-- 导出表中的数据 `good_tbl`
--
INSERT INTO `good_tbl` VALUES (1, 2);
INSERT INTO `good_tbl` VALUES (2, 3);
INSERT INTO `good_tbl` VALUES (3, 2);
--
-- 表的结构 `brand_tbl`
--
CREATE TABLE `brand_tbl` (
`brand_id` int(10) unsigned NOT NULL auto_increment,
`brand_name` varchar(50) NOT NULL,
PRIMARY KEY (`brand_id`)
) ENGINE=MyISAM DEFAULT CHARSET=gbk AUTO_INCREMENT=4 ;
--
-- 导出表中的数据 `brand_tbl`
--
INSERT INTO `brand_tbl` VALUES (1, '诺基亚');
INSERT INTO `brand_tbl` VALUES (3, '三星');