从一张桌子匹配战士

时间:2014-04-16 01:22:46

标签: mysql sql

我有一张战斗机记录的表格,我需要根据战斗运动的等级,重量,性别和类型来匹配它们。这是表格的结构

CREATE TABLE `tfc_sparring_requests_athletes` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `fullname` varchar(300) DEFAULT NULL,
  `birthdate` date DEFAULT NULL,
  `weight` float DEFAULT NULL,
  `fightsport` int(11) DEFAULT NULL,
  `sex` int(11) DEFAULT NULL,
  `level` int(11) DEFAULT NULL,
  `teamid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8

我试图像这样进行查询以匹配战士

select a.fullname,b.fullname,a.weight
    from tfc_sparring_requests_athletes a ,
             tfc_sparring_requests_athletes b 
where a.weight = b.weight
    and a.fightsport = b.fightsport 
    and a.level =b.level 
    and a.sex = b.sex 
    and a.fullname != b.fullname

,结果是

fighter23   fighter1    78
fighter6    fighter5    70
fighter5    fighter6    70
fighter1    fighter23   78
fighter26   fighter25   57
fighter25   fighter26   57
fighter28   fighter27   80
fighter27   fighter28   80

正如你所看到的,战斗机1与第1排中的战斗机23相匹配,但在第4排中,战斗机再次出现。其他战士也会像第2行和第3行中的战斗机5和6一样重复他们的比赛。我怎样才能避免这种重复,以便我能够独特地展示比赛?

1 个答案:

答案 0 :(得分:3)

无论如何,我找到了基于这个问题的解决方案How to select distinct pairs in MySQL join (same table) with transitivity?

select MIN(a.id),b.id,a.fullname name1,b.fullname name2,a.weight
    from tfc_sparring_requests_athletes a ,tfc_sparring_requests_athletes b 
where a.weight = b.weight
    and a.fightsport = b.fightsport 
    and a.level =b.level 
    and a.sex = b.sex 
    and a.fullname != b.fullname
    AND b.id > a.id
GROUP BY b.id;