Mysql Query选择重复项

时间:2013-12-07 19:48:12

标签: mysql

我的数据库中有一个名为Player的表,它看起来像这样

 id    placex    placey    wealth    strenght    goalx    goaly 
 ---------------------------------------------------------------    
  1     500        20       3335      2500      500      440 
  2     500        20       777      2000        20      500 
  3      20       500       1000      2000      500       20 
  4     500       440       1000      2000       20       20 

我需要一个能够在玩家位于同一位置的条件下显示id和财富的查询,因此应该有一个placex副本,不同玩家的placey

在这张表中,我们将在同一个地方拥有身份1的玩家和身份2的玩家,我写了这个

SELECT 
    id, placex, placey, wealth 
FROM 
    Player 
WHERE 
    placex IN (SELECT placex FROM Player HAVING COUNT(id) > 1);

我将此作为输出

+----+--------+--------+--------+
| id | placex | placey | wealth |
+----+--------+--------+--------+
|  1 |    500 |     20 |   3335 |
|  2 |    500 |     20 |    777 |
|  4 |    500 |    440 |   1000 |
+----+--------+--------+--------+

我需要消除ID为4的玩家,所以如何修改我的查询以包含重复的玩具

我希望得到这个

| id | placex | placey | wealth |
   1   500        20      3335
   2   500        20       777

4 个答案:

答案 0 :(得分:1)

运行这个,让我知道你的结果:

SELECT A.id, A.placex, A.placey, A.wealth
FROM Player A,
     ( SELECT  placex, placey
       FROM Player
       GROUP BY placex, placey
       HAVING COUNT(*) > 1
     ) B
WHERE A.placex = B.placeX
AND A.placey = B.placey

答案 1 :(得分:0)

Select id, wealth From Player 
inner Join (
Select PlaceX, PlaceY From Player Having(count(id) > 1) Occupied
On Occupied.PlaceX = Player.PlaceX and Occupied.PlaceY = Player.PlaceY

在子查询为您提供更多选项之前,请始终查看联接。

答案 2 :(得分:0)

SELECT  id,placex,placey,wealth FROM player WHERE placey IN(
SELECT  placey FROM Player
GROUP BY placey 
HAVING COUNT(placey)>1)

SQL Fiddle

答案 3 :(得分:0)

SELECT p1.id, p1.wealth
FROM Player AS p1
INNER JOIN Player AS p2
ON (p1.id <> p2.id AND p1.PlaceX = p2.PlaceX AND p1.PlaceY = p3.PlaceY)
GROUP BY p1.id

您还应该添加索引以将PlaceX和PlaceY一起编入索引。