我们说我有一个包含三列的表 - 身份证,姓名和性别。可能有多个具有相同名称的ID。可能还有多个同名的性别。
对于除了一个名字以外的所有名字,我完全可以,因为女性和男性都有一排,而对于双性人则有一排,依此类推。然而,对于丹尼尔和唯一的丹尼尔,我不能允许那里有男性排和女性排(尽管双性人等完全没问题)。如果男性和女性排都有丹尼尔的名字,我想排除男性排,只留下女排和其他任何性别。
id | name | gender
---+--------+---------
1 | Andrew | male
1 | Andrew | female
2 | Andrew | female
1 | Megan | male
1 | Megan | female
1 | Megan | intersex
2 | Megan | male
2 | Megan | female
4 | Megan | intersex
1 | Daniel | male -- this row must be eliminated...
1 | Daniel | female -- beacuse this row is present.
1 | Daniel | intersex -- But this one is totally cool.
1 | Daniel | porcupine -- So is this one.
2 | Daniel | male -- this row must be eliminated...
2 | Daniel | female -- beacuse this row is present.
3 | Daniel | male -- But this row is totally cool,
-- because there's no female Daniel row
-- with an id of 3.
如何删除这些行?我有一种潜在的怀疑,我错过了一些非常明显的东西......
答案 0 :(得分:4)
这应该这样做:
DELETE FROM tablename t WHERE name='Daniel' AND gender='male'
AND EXISTS (SELECT 1 FROM tablename
WHERE name='Daniel' AND id=t.id AND gender='female');