目录
题目
准备数据
分析数据
总结
题目
写一个 SQL 查询语句,以报告在给定三个实验平台中每种实验完成的次数。请注意,每一对(实验平台、实验名称)都应包含在输出中,包括平台上实验次数是零的。
结果可以以任意顺序给出.
准备数据
Create table If Not Exists Experiments (experiment_id int, platform ENUM('Android', 'IOS', 'Web'), experiment_name ENUM('Reading', 'Sports', 'Programming'))
Truncate table Experiments
insert into Experiments (experiment_id, platform, experiment_name) values ('4', 'IOS', 'Programming')
insert into Experiments (experiment_id, platform, experiment_name) values ('13', 'IOS', 'Sports')
insert into Experiments (experiment_id, platform, experiment_name) values ('14', 'Android', 'Reading')
insert into Experiments (experiment_id, platform, experiment_name) values ('8', 'Web', 'Reading')
insert into Experiments (experiment_id, platform, experiment_name) values ('12', 'Web', 'Reading')
insert into Experiments (experiment_id, platform, experiment_name) values ('18', 'Web', 'Programming')
experiments表
分析数据
方法一
select platform,experiment_name,count(e1.platform) as num_experiments from
(select distinct platform from experiments) p
cross join (select distinct experiment_name from experiments) e
left join experiments e1
using(platform, experiment_name)
group by platform,experiment_name;
方法二
with pe as
( select * from
(
select 'IOS' platform
union all
select 'Android' platform
union all
select 'Web' platform
)p
cross join
(
select 'Programming' experiment_name
union all
select 'Sports' experiment_name
union all
select 'Reading' experiment_name
)e
)
select pe.platform,pe.experiment_name,count(w.platform) as num_experiments
from pe
left join Experiments as w
using(platform,experiment_name)
group by platform,experiment_name;
总结
- 方法一:使用distinct,但是不严谨,可能例子中含有platform或者experiment_name少于3个的情况,从而丢失情况.方法二:使用union的方法枚举
- left join Experiments表,using(platform,experiment_name)即可保全左表所有结构,这里不需要ifnull,因为count对null计数就会返回0。
using的使用情况和on一样,但是可以避免on子句中重复列名
假设有两个表
employees
和departments
,它们都有一个名为department_id
的列,你想要根据这个列将这两个表连接起来:SELECT e.name, d.department_name FROM employees e JOIN departments d USING (department_id);
等同于使用on子句
SELECT e.name, d.department_name FROM employees e JOIN departments d ON e.department_id = d.department_id;