如何在应用排序时删除mysql结果中的重复项

6qftjkof  于 2023-03-11  发布在  Mysql
关注(0)|答案(1)|浏览(73)

我有以下表格和数据:

CREATE TABLE `a_athletes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
);

CREATE TABLE `a_events` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `athlete_id` bigint(20) DEFAULT NULL,
  `date` date DEFAULT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `a_events` (`id`, `name`, `athlete_id`, `date`) VALUES
(1, 'Long jump', 1, '2023-02-18'),
(2, 'Row', 1, '2023-02-09'),
(3, 'Sprint', 2, '2023-02-10'),
(4, 'Sprint', 1, '2023-02-14'),
(5, 'Long Jump', 2, '2023-02-20');

INSERT INTO `a_athletes` (`id`, `name`) VALUES
(1, 'Sarah'),
(2, 'Simon'),
(3, 'Barbera');

我想得到所有的结果,其中运动员没有'行'事件相关联。
我有以下查询来实现这一点:

select * 
from a_athletes
left join a_events on a_athletes.id = a_events.athlete_id
where a_athletes.id not in (
    select a_athletes.id
    from a_athletes
    inner join a_events on a_athletes.id = a_events.athlete_id
    where a_events.`name` = 'Row'
)
 order by a_events.`date`;

得出以下结果:

3,Barbera,NULL,NULL,NULL,NULL
2,Simon,3,Sprint,2,2023-02-10
2,Simon,5,Long Jump,2,2023-02-20

我想在运动员的UI表中显示这些结果,不重复。我想忽略a_athletes.id已经出现在结果中之后的任何结果。结果需要分页,所以这必须在sql查询中完成。
在本例中,预期输出为:

3,Barbera,NULL,NULL,NULL,NULL
2,Simon,3,Sprint,2,2023-02-10

我怎样才能做到这一点?

gudnpqoy

gudnpqoy1#

您可以尝试以下查询

SELECT *
FROM   a_athletes a1
       LEFT JOIN a_events e1
              ON a1.id = e1.athlete_id
WHERE  NOT EXISTS (SELECT 1
                   FROM   a_events e2
                   WHERE  a1.id = e2.athlete_id 
                      AND e2.`name` = 'Row')
   AND NOT EXISTS (SELECT 1
                   FROM   a_events e3
                   WHERE  a1.id = e3.athlete_id 
                      AND e1.id > e3.id)   
ORDER  BY e1.`date`;

参见here演示

相关问题