2014-04-16 70 views
2

我有一張戰鬥機記錄表,我需要根據等級,體重,性別和戰鬥類型來匹配它們。這是表的從單一表格匹配戰士

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一樣。我怎樣才能避免這種重複,這樣我就可以獨特地展示比賽了?

回答

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; 
解決方案