你可以尝试这样的事情:
drop table if exists ids;
create table ids (score int unsigned primary key)
select distinct rpo as score from rank
union
select distinct rsp as score from rank
union
select distinct rsv as score from rank;
select ids.score,
sum(if(rank.rpo=ids.score,1,0)) as RPO,
sum(if(rank.rsp=ids.score,1,0)) as RSP,
sum(if(rank.rsv=ids.score,1,0)) as RSV
from ids,round
left join base on round.id = base.round_id
left join rank on round.id = rank.round_id and rank.number = base.number
where base.result = 1
and round.round_date between '2013-03-15' and '2013-03-22'
and round.gameform = 'V4'
and round.gameform not like "OSPEC"
group by ids.score with rollup;
如果您不想创建临时表,可以尝试:
select ids.score,
sum(if(rank.rpo=ids.score,1,0)) as RPO,
sum(if(rank.rsp=ids.score,1,0)) as RSP,
sum(if(rank.rsv=ids.score,1,0)) as RSV
from
(
select distinct rpo as score from rank
union
select distinct rsp as score from rank
union
select distinct rsv as score from rank
) ids, round
left join base on round.id = base.round_id
left join rank on round.id = rank.round_id and rank.number = base.number
where base.result = 1
and round.round_date between '2013-03-15' and '2013-03-22'
and round.gameform = 'V4'
and round.gameform not like "OSPEC"
group by ids.score with rollup;
有关工作示例,请参见http://sqlfiddle.com/#!2/9b7d7/6 。