表名称:course_trainer_combination
创建表查询:
create table `course_trainer_combination` (
`id` double ,
`course` varchar (150),
`trainer` varchar (150),
`distance` float
);
insert into `course_trainer_combination` (`id`, `course`, `trainer`, `distance`) values('1','Course A','Trainer A','110.00');
insert into `course_trainer_combination` (`id`, `course`, `trainer`, `distance`) values('2','Course A','Trainer B','105.00');
insert into `course_trainer_combination` (`id`, `course`, `trainer`, `distance`) values('3','Course A','Trainer C','115.00');
insert into `course_trainer_combination` (`id`, `course`, `trainer`, `distance`) values('4','Course B','Trainer A','112.00');
insert into `course_trainer_combination` (`id`, `course`, `trainer`, `distance`) values('5','Course B ','Trainer B','108.00');
insert into `course_trainer_combination` (`id`, `course`, `trainer`, `distance`) values('6','Course B','Trainer C','109.00');
insert into `course_trainer_combination` (`id`, `course`, `trainer`, `distance`) values('7','Course C','Trainer A','124.00');
insert into `course_trainer_combination` (`id`, `course`, `trainer`, `distance`) values('8','Course C','Trainer B','128.00');
insert into `course_trainer_combination` (`id`, `course`, `trainer`, `distance`) values('9','Course C','Trainer C','121.00');
我的桌子就像
预期结果:
2 | Course A | Trainer B | 105
6 | Course B | Trainer C | 109
7 | Course C | Trainer A | 124
答案 0 :(得分:1)
您可以使用相关子查询
select ct.*
from course_trainer_combination ct
where ct.distance = (select min(ct1.distance)
from course_trainer_combination ct1
where ct1.course = ct.course
);
如果使用的是较新版本,则可以使用分析功能:
select ct.*
from (select ct.*,
rank() over (partition by ct.course order by ct.distance) as seq
from course_trainer_combination ct
) ct
where ct.seq = 1;
答案 1 :(得分:0)
另一种方法可能如下。
select id,
m.course,
trainer,
m.distance
from course_trainer_combination m
inner join (select course,
Min(distance) distance
from course_trainer_combination
group by course)t
on t.course = m.course
and t.distance = m.distance
注意:如果两名教练在1个课程中的距离相同,则会显示两个记录。
答案 2 :(得分:0)
解决此问题的一种方法是:
使用mysql user variable跟踪已选择的教练,并使用FIND_IN_SET()检查教练已分配给课程的天气:
SET @selectedTrainers :='';
SELECT *, @selectedTrainers := CONCAT(@selectedTrainers, ',', a.trainer) AS selectedTrainers
FROM `course_trainer_combination` a
where NOT EXISTS (
SELECT 1
FROM `course_trainer_combination` b
WHERE b.course = a.course
AND a.distance > b.distance
AND FIND_IN_SET(b.trainer, @selectedTrainers) = 0
)
AND FIND_IN_SET(a.trainer, @selectedTrainers) = 0