mysql:删除带有条件的重复值的行(重复列)

时间:2015-09-22 15:42:27

标签: mysql stored-procedures

我有一个表“玩家”如下 哪里: ID是主键。

  • 日期=他们玩的日期(仅1个月,因此可以从1到31)
  • 姓名=球员姓名
  • 体育=他们玩的运动,名单上可以有很多运动;但我只专注于那些玩“足球”并且在一天内玩超过2场比赛的人

这是表“玩家”。

+----+------------+-------+-------------+
| ID | Date       | Name  | Sport       |
+----+------------+-------+-------------+
|  1 |          1 | A     | football    |
|  2 |          1 | A     | soccer      |
|  3 |          3 | A     | tennis      |
|  4 |          2 | B     | tennis      |
|  5 |          2 | B     | football    |
|  6 |          1 | C     | basketball  |
|  7 |          1 | C     | tennis      |
|  8 |          1 | C     | fishing     |
|  9 |          4 | D     | football    |
+----+------------+-------+-------------+

我想查找不参与的人员名单(姓名和运动):

  • 在一天内练习“足球”+其他运动。

注意:如果某人在一天内玩“足球”+其他游戏,我们会将其从当天的列表中删除。只有在那一天才能删除他。

所以结果应该是这样的,

+----+------+------+-----------+
| ID | Date | Name |  Sport    |
+----+------+------+-----------+
|  3 |    3 | A    | tennis    |
|  6 |    1 | C    | basketball|
|  7 |    1 | C    | tennis    |
|  8 |    1 | C    | fishing   |
|  9 |    4 | D    | football  |
+----+------+------+-----------+

这是列出的后续问题 mysql: find rows with repeated values plus condition

谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你想获得在那个日期只参加过一项运动或没有踢足球的球员的日期和名字:

SELECT   Date, Name
FROM     player
GROUP BY Date, Name
HAVING   COUNT(DISTINCT Sport) = 1
      OR NOT SUM(Sport='football')

sqlfiddle上查看。

如果您想查看他们玩过哪些体育项目和/或获得相关记录的ID,您可以将上述内容加入player表:

SELECT * FROM player NATURAL JOIN (
  SELECT   Date, Name
  FROM     player
  GROUP BY Date, Name
  HAVING   COUNT(DISTINCT Sport) = 1
        OR NOT SUM(Sport='football')
) t

sqlfiddle上查看。

答案 1 :(得分:1)

你应该寻找这个:

此处,我们在key record values (date + name)key record values (date + name) who played football的交叉点中省略了key record values (date + name) who did not play football这些匹配

SELECT 
    p1.*
FROM
    player p1
        LEFT JOIN
    (SELECT 
        pnfb.*
    FROM
        (SELECT 
        date, name
    FROM
        player
    WHERE
        sport <> 'football') pnfb
    JOIN (SELECT 
        date, name
    FROM
        player
    WHERE
        sport = 'football') pfb ON (pnfb.date = pfb.date
        AND pnfb.name = pfb.name)) p2 ON (p1.date = p2.date AND p1.name = p2.name)
WHERE
    p2.date IS NULL;