本文共 1827 字,大约阅读时间需要 6 分钟。
SQL join用来把来自两个或多个表的行结合起来,下图展示了LEFT JOIN、RIGHT JOIN、INNER JOIN、OUTER JOIN相关的七种用法:
创建数据库:
create database if not exists test default charset utf8 collate utf8_general_ci;use test;SET NAMES utf8;SET FOREIGN_KEY_CHECKS = 0;DROP TABLE IF EXISTS `Websites`;CREATE TABLE `Websites` ( `id` int(11) NOT NULL, `name` char(20) NOT NULL DEFAULT '', `url` char(30) NOT NULL DEFAULT '', `alexa` int(11) NOT NULL, `country` char(10) NOT NULL DEFAULT '', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;DROP TABLE IF EXISTS `access_log`;CREATE TABLE `access_log` ( `aid` int(11) NOT NULL, `site_id` int(11) NOT NULL, `count` int(11) NOT NULL, `date` datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8;BEGIN;INSERT INTO `Websites` VALUES ('1', 'Google', 'https://www.google.cm/', '1', 'USA'), ('2', 'TaoBao', 'https://www.taobao.cm/', '13', 'CN'), ('3', 'CaiNiao', 'https://www.runoob.cm/', '4689', 'CN'), ('4', 'Weibo', 'https://www.weibo.cm/', '20', 'CN'), ('5', 'Facebook', 'https://www.facebook.cm/', '3', 'USA'), ('7', 'stackoverflow', 'https://www.stackoverflow.cm/', '0', 'IND');COMMIT;BEGIN;INSERT INTO `access_log` VALUES ('1', '1', '45', '2016-05-10'), ('2', '3', '100', '2016-05-13'), ('3', '1', '230', '2016-05-14'), ('4', '2', '10', '2016-05-14'), ('5', '5', '205', '2016-05-14'), ('6', '4', '13', '2016-05-15'), ('7', '3', '220', '2016-05-15'), ('8', '5', '545', '2016-05-16'), ('9', '3', '201', '2016-05-17');COMMIT;
查看数据库:
SELECT Websites.id, Websites.name, access_log.count, access_log.dateFROM WebsitesINNER JOIN access_logON Websites.id=access_log.site_id;
输出如下:
转载地址:http://xntx.baihongyu.com/