MySQL 使用不同条件下的关系进行删除

MySQL DELETE using relationships with different conditions

+--------+---------------------+--------+------------+--------------------------------------------------------------+-------+------------+------+--------+-------+
| UserID | email               | name   | surname    | password                                                     | place | birthDay   | male | female | admin |
+--------+---------------------+--------+------------+--------------------------------------------------------------+-------+------------+------+--------+-------+
|     10 | elo@elo.pl          | elo    | elo        | b$JPdUjCFv2mtoG3b2Dx0v1.D5089S4wUsg0aS21joLhlrzb1f4X3sW | stg   | 2000-12-09 |    1 |      0 |     1 |
|     11 | kacper@wp.pl        | kacper | kacper     | b$mlKWmIwdmj8Q0Py36H3m1O2REqYD9VBacmmk8jiogBIfrUmKy4XpG | stg   | 0000-00-00 |    1 |      0 |     0 |
|     12 | filip@galikowski.pl | filip  | galikowski | bcxOXVs/tHytGE/j0nA/s.wdxOherYlJf18F3EA/elvUblEN99pLy | stg   | 0000-00-00 |    1 |      0 |     0 |
|     13 | kacper@niemczyk.pl  | kacper | niemczyk   | b$YoSDXFc/t.jr5K8EFrY16OH8jom6kylCqvdFL7FfL2rdrO6hVzxCa | stg   | 0000-00-00 |    1 |      0 |     0 |
+--------+---------------------+--------+------------+--------------------------------------------------------------+-------+------------+------+--------+-------+

+--------+------------+
| UserID | FollowerID |
+--------+------------+
|     12 |         13 |
|     10 |         13 |
+--------+------------+

我需要用观察者的电子邮件和被观察者的电子邮件删除给定的行。

例如

我收到电子邮件:"kacper@niemczyk.pl" 和 "elo@elo.pl",我必须从关注 table 中删除这些人。在此示例中,删除 UserID = 10 和 FollowerID = 13

的行

我知道可以通过电子邮件找到一个 ID 然后将其删除,但我也知道在关系的帮助下可以更快地完成,但我不知道如何。

以此为参考:

create table users (id int, name varchar(10));
insert into users values (1, 'Kacper'),(2, 'Krzysztof'), (3, 'Kuba');
create table followers (userid int, followerid int);
insert into followers values (1, 2), (1, 3);
--now we want to delete from followers records, where Krzysztof follows Kacper
delete from followers
where exists (select 1 from users
              where id = followers.userid and name = 'Kacper')--followed user
  and exists (select 1 from users
              where id = followers.followerid and name = 'Krzysztof');--follower

编辑评论

要以类似的方式将记录添加到 followers,请使用:

insert into followers
select u1.id, u2.id from users u1
cross join users u2
where u1.name = 'Kacper' --followed user
  and u2.name = 'Krzysztof' --follower