CREATE TABLE `product` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`amount` INT(10) UNSIGNED DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `product_details` (
`id` INT(10) UNSIGNED NOT NULL,
`weight` INT(10) UNSIGNED DEFAULT NULL,
`exist` INT(10) UNSIGNED DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO product(id,amount) VALUES (1,100),(2,200),(3,300),(4,400);
INSERT INTO product_details(id,weight,exist) VALUES (2,22,0),(4,44,1),(5,55,0),(6,66,1);
SELECT * FROM product;
SELECT * FROM product_details;
一、左外链接查询
SELECT * FROM product
LEFT JOIN product_details
ON (product.`id` = product_details.`id`);
(51CTO加水印真low!)
SELECT * FROM product LEFT JOIN product_details
ON (product.id = product_details.id)
AND product_details.id=2;
这个查询使用ON条件决定了从LEFT JOIN的product_details表中检索符合的所有数据行。
SELECT * FROM product LEFT JOIN product_details
ON (product.id = product_details.id)
WHERE product_details.id=2;
这个查询做了LEFT JOIN,然后使用WHERE子句从LEFT JOIN的数据中过滤掉不符合条件的数据行。
再看例子:
SELECT * FROM product LEFT JOIN product_details
ON product.id = product_details.id
AND product.amount=100;
所有来自product表的数据行都被检索到了,但没有在product_details表中匹配到记录
(product.id = product_details.id AND product.amount=100 条件并没有匹配到任何数据)
SELECT * FROM product LEFT JOIN product_details
ON (product.id = product_details.id)
AND product.amount=200
所有来自product表的数据行都被检索到了,有一条数据匹配到了。
从上述可知:WHERE条件发生在匹配阶段之后!