查询以查找最近的远程教练

时间:2019-02-21 11:11:31

标签: mysql sql

表名称: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');

我的桌子就像

enter image description here

预期结果:

2 | Course A | Trainer B | 105
6 | Course B | Trainer C | 109
7 | Course C | Trainer A | 124

3 个答案:

答案 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