MySQL多表子查询面试题
1.题目
有三张数据表,结构如下:
人员表:人员姓名,人员id
销售表:人员id,时间,销售金额
花费表:人员id,时间,花费金额
写一条SQL语句,完成下面的统计结果:
人员姓名,总花费,总销售
注意:需要使用子查询,三张表关联不行,会出现重复数据。
2.创建数据库
创建库、表以及插入若干表记录,用于测试: -- 删除并重建test库,进入test库;
drop database if exists test; create database if not exists test charset utf8; use test;
-- 创建用户表(user),人员id(id),人员姓名(name)
create table user(id int,name varchar(20)); insert into user values(1, A); insert into user values(2, B);
-- 创建销售额表(sale),人员id(userid),时间(sale_time),销售金额(sale_money)
create table sale(userid int,sale_time date, sale_money double); insert into sale values(1, 2019-2-21, 1000); insert into sale values(1, 2019-2-22, 600); insert into sale values(2, 2019-2-23, 1500); insert into sale values(2, 2019-2-24, 800);
-- 创建花费额表(cost),人员id(userid),时间(cost_time),花费金额(cost_money)
create table cost(userid int,cost_time date, cost_money double); insert into cost values(1, 2019-2-23, 900); insert into cost values(1, 2019-2-24, 800); insert into cost values(2, 2019-2-25, 1400); insert into cost values(2, 2019-2-26, 1600);
执行以上SQL,查询sale和cost表中的所有记录,效果如下:
销售表(sale)如下:
花费表(cost)如下:
3.根据题意,给出如下SQL语句:
-- 1.查询每个人的总销售额:
select user.name, sum(sale_money) from user, sale where user.id=sale.userid group by user.id;
-- 2.查询每个人的总花费额:
select user.name, sum(sale_money) from user, sale where user.id=sale.userid group by user.id;
-- 3.把上面两个查询的结果作为表,进行关联查询:
select t1.name, 总销售额, 总花费额 from ( select user.id as id, user.name as name, sum(sale_money) 总销售额 from user, sale where user.id=sale.userid group by user.id ) t1, ( select user.id as id, user.name, sum(cost_money) 总花费额 from user, cost where user.id=cost.userid group by user.id ) t2 where t1.id = t2.id;