从同一个表中查找重复项并从sql

时间:2017-01-18 14:35:47

标签: mysql

哦,我的头衔不是最好的,因为英语不是我的主要语言,如果他们在这里理解了这个问题,也许有人可以解决这个问题而不是贬低。

基本上我有两张桌子 - 游戏玩家和结果。 Tourneyplayers就像一个边桌,可以在多个牌桌上收集锦标赛信息 - 结果,锦标赛,球员等。我想在第一场锦标赛的第一场比赛中检查结果表中的重复项,然后返回所有有重复赛的锦标赛玩家。

Tourneyplayers包含行:

Tourneyplayers
tp_id | resultid | tourneyid
1     | 2        | 91
2     | 21       | 91
3     | 29       | 91
4     | 1        | 91
5     | 3        | 92

结果包含行:

Results:
r_id | day1_best
1    | 3
2    | 1
3    | 4
..   | ..
21   | 1
..   | ..
29   | 2

现在id = 91的锦标赛共有4个结果,id为1,2,21和29.我想返回有重复的值,所以目前结果是

Result
tp_id | resultid | day1_best
1     | 2        | 1
2     | 21       | 1

我尝试写这样的东西:

SELECT * 
FROM tourneyplayers
WHERE resultid
IN (

SELECT r1.r_id
FROM results AS r1
INNER JOIN results AS r2 ON ( r1.day1_best = r2.day1_best ) 
AND (
r1.r_id <> r2.r_id
)
)
AND tourneyid =91

但是除了具有相同day1_best的值之外,它还选择了另外两个不具有相同值的值。我怎样才能改进我的SQL或重写它?

2 个答案:

答案 0 :(得分:0)

首先你JOIN两个表,所以你知道数据的样子。

SELECT *
FROM tourney_players t
JOIN results r
  ON t.`resultid` = r.`r_id`;

然后使用相同的查询GROUP查看tourneyid, day1_best组合有多行

SELECT `tourneyid`, `day1_best`, count(*) as total
FROM tourney_players t
JOIN results r
  ON t.`resultid` = r.`r_id`
GROUP BY `tourneyid`, `day1_best`;  

最后,您使用基础JOIN并执行LEFT JOIN以查看哪些行匹配并仅显示这些行。

SELECT t.`tp_id`, r.`r_id`, r.`day1_best`
FROM tourney_players t
JOIN results r
  ON t.`resultid` = r.`r_id`
LEFT JOIN (SELECT `tourneyid`, `day1_best`, count(*) as total
           FROM tourney_players t
           JOIN results r
             ON t.`resultid` = r.`r_id`
           GROUP BY `tourneyid`, `day1_best`
           HAVING count(*) > 1) as filter           
  ON t.`tourneyid` = filter.`tourneyid`
 AND r.`day1_best` = filter.`day1_best`
WHERE filter.`tourneyid` IS NOT NULL;

<强> SQL DEMO

<强>输出

enter image description here

答案 1 :(得分:-1)

请试试这个:

   Select tp.tp_id , tp.resultid ,r.day1_best from (Select * from Tourneyplayers 
where tourneyid = 91)as tp inner join (select * from Result day1_best in(select 
day1_best from result group by day1_best having count(*)>1 ) )as r on tp.resultid  
= r.r_id ;