如果另一行SQL中存在来自1行的值,则删除重复行

时间:2015-05-27 13:01:46

标签: mysql duplicates

我在删除所有具有特定值的行时遇到问题,然后删除与已删除的行列具有相同值的其他行。 以下是我现在所拥有的一个例子:

SELECT Race.intRaceID, Register.intRegID, Member.intMemberID
FROM Race
LEFT JOIN Register ON Race.intRaceID=Register.intRaceID
LEFT JOIN Member ON Register.intMemberID=Member.intMemberID

给了我:

+------------+-----------+-------------+
| intRaceID  | intRegID  | intMemberID |
+------------+-----------+-------------+
|       100  | 10        | 1           |
|       100  | 40        | 2           |
|       200  | NULL      | NULL        |
|       300  | 30        | 2           |
|       400  | 20        | 4           |
|       500  | NULL      | NULL        |
+------------+-----------+-------------+

所以,我试图做的是删除一个特定的intMemberID(保留NULL)和它们所关联的所有intRaceID。 我添加了

WHERE Member.intMemberID <> 2 OR Member.intMemberID IS NULL

给出结果:

+------------+-----------+-------------+
| intRaceID  | intRegID  | intMemberID |
+------------+-----------+-------------+
|       100  | 10        | 1           |
|       200  | NULL      | NULL        |
|       400  | 20        | 4           |
|       500  | NULL      | NULL        |
+------------+-----------+-------------+

但不会删除与intMemberID关联的所有intRaceID。 任何帮助将不胜感激

我试图展示的表是:

+------------+-----------+-------------+
| intRaceID  | intRegID  | intMemberID |
+------------+-----------+-------------+
|       200  | NULL      | NULL        |
|       400  | 20        | 4           |
|       500  | NULL      | NULL        |
+------------+-----------+-------------+

1 个答案:

答案 0 :(得分:0)

我认为您必须编写WHERE子句,如以下查询中所示:

SELECT Race.intRaceID, Register.intRegID, Member.intMemberID
FROM Race
LEFT JOIN Register ON Race.intRaceID = Register.intRaceID
LEFT JOIN Member ON Register.intMemberID = Member.intMemberID
WHERE Race.intRaceID NOT IN (
   SELECT Race.intRaceID
   FROM Race 
   INNER JOIN Register ON Race.intRaceID = Register.intRaceID
   INNER JOIN Member ON Register.intMemberID = Member.intMemberID
   WHERE Member.intMemberID = 2)
ORDER BY intRaceID;

这样您就可以排除intRaceIDintMemberID相关的所有记录,其值为2

Demo here