@爱学习的阿朵
目录
1、数据说明
- 用到了菜鸟教程里的2个表:websites和access_log。两表信息如下图所示。
- 表的创建:
drop table websites
create table websites
(
id varchar(30),
name varchar(30),
url varchar(30),
alexa varchar(30),
country varchar(30));
----------------------------------------------------------------------------------------
INSERT INTO websites VALUES ('1', 'Google', 'https://www.google.cm/', '1', 'USA');
INSERT INTO websites VALUES('2', '淘宝', 'https://www.taobao.com/', '13', 'CN');
INSERT INTO websites VALUES('3', '菜鸟教程', 'http://www.runoob.com/', '4689', 'CN');
INSERT INTO websites VALUES('4', '微博', 'http://weibo.com/', '20', 'CN');
INSERT INTO websites VALUES('5', 'Facebook', 'https://www.facebook.com/', '3', 'USA');
select * from websites
create table access_log(
aid varchar(30),
site_id varchar(30),
counts varchar(30),
dates varchar(30));
INSERT INTO access_log VALUES('1','1','45','2016-05-10');
INSERT INTO access_log VALUES('2','3','100','2016-05-13');
INSERT INTO access_log VALUES('3','1','230','2016-05-14');
INSERT INTO access_log VALUES('4','2','10','2016-05-14');
INSERT INTO access_log VALUES('5','5','205','2016-05-14');
INSERT INTO access_log VALUES('6','4','13','2016-05-15');
INSERT INTO access_log VALUES('7','3','220','2016-05-15');
INSERT INTO access_log VALUES('8','5','545','2016-05-16');
INSERT INTO access_log VALUES('9','3','201','2016-05-17');
select * from access_log
1.1 websites表(5行)
1.2 access_log表(9行)
2、join…on 的用法
- SQL的执行顺序
1、from 表
2、where 条件
3、group by
4、select 的字段;
5、order by 对结果集进行排序
- 含义:只输出匹配的行。 - (1)代码(access_log在前,websites在后)
select *
from access_log a
join websites w on w.id=a.aid
- (1) 结果(access_log在前,websites在后)
- (2) 代码(websites在前,access_log在后)
select * from websites w
join access_log a on w.id=a.aid
- (2) 结果
3、left join的用法
- 含义:用右表去和左表匹配,如果没有匹配上的,则返回空行。
3.1 当左表为websites(5行),右表为access_log(9行)
- 代码
select * from websites w
left join access_log a on w.id=a.aid
- 结果
3.2 当左表为access_log(9行),右表为websites(5行)
- 代码
select * from access_log a
left join websites w on w.id=a.aid
- 结果
4、group by回顾
- 代码
select count(country)from websites
group by country
- 结果