/**建立表**/ /**建立表1**/ 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; /**建立表2**/ 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;
1、左外連接查詢sql
/**左鏈接查詢**/ SELECT * FROM product LEFT JOIN product_details ON (product.`id` = product_details.`id`);
(51CTO加水印真low!)ide
SELECT * FROM product LEFT JOIN product_details ON (product.id = product_details.id) AND product_details.id=2;
這個查詢使用ON條件決定了從LEFT JOIN的product_details表中檢索符合的全部數據行。spa
SELECT * FROM product LEFT JOIN product_details ON (product.id = product_details.id) WHERE product_details.id=2;
這個查詢作了LEFT JOIN,而後使用WHERE子句從LEFT JOIN的數據中過濾掉不符合條件的數據行。blog
再看例子:it
SELECT * FROM product LEFT JOIN product_details ON product.id = product_details.id AND product.amount=100;
全部來自product表的數據行都被檢索到了,但沒有在product_details表中匹配到記錄class
(product.id = product_details.id AND product.amount=100 條件並無匹配到任何數據)im
SELECT * FROM product LEFT JOIN product_details ON (product.id = product_details.id) AND product.amount=200
全部來自product表的數據行都被檢索到了,有一條數據匹配到了。數據
從上述可知:WHERE條件發生在匹配階段以後!
查詢