SQL查询:删除连接表中不存在的条目?

时间:2010-04-12 06:42:55

标签: mysql

我要删除所有没有订阅的用户,但每次尝试检测用户时我都会遇到问题。

我的模式看起来像这样:

用户= {用户ID ,名称}

订阅费用= {用户ID ,订阅名称}

现在,我要做的是删除useroffering表中计数为零的用户表中的所有用户。或换句话说:userid不在subscriptionoffering表中的所有用户。我尝试过不同的查询但没有结果。

我试图说where user.userid <> subscriptionoffering.userid,但这似乎不起作用。有谁知道如何创建正确的查询?

由于

Mestika

2 个答案:

答案 0 :(得分:1)

delete from Users 
where UserID not in
    (select userid from subscriptionOffering)

答案 1 :(得分:1)

您可以使用带有delete的多表left outer join语句,并专注于不匹配的行,如下所示:

delete u from Users as u
left outer join Subscriptionoffering as so
on so.userid = u.userid
where so.userid is null;

以下是一些测试代码来证明它:

mysql> create table Users (userid int unsigned primary key auto_increment) engine = innodb;
Query OK, 0 rows affected (0.43 sec)

mysql> create table Subscriptionoffering (userid int unsigned not null, subscriptionname varchar(32) not null, foreign key (userid) references Users(userid)) engine = innodb;
Query OK, 0 rows affected (0.41 sec)

mysql> insert into Users () values (), (), (), (), ();
Query OK, 5 rows affected (0.38 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> select * from Users;
+--------+
| userid |
+--------+
|      1 |
|      2 |
|      3 |
|      4 |
|      5 |
+--------+
5 rows in set (0.00 sec)

mysql> insert into Subscriptionoffering (userid, subscriptionname) values (1, 'One'), (3, 'Three'), (5, 'Five');
Query OK, 3 rows affected (0.31 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from Subscriptionoffering;
+--------+------------------+
| userid | subscriptionname |
+--------+------------------+
|      1 | One              |
|      3 | Three            |
|      5 | Five             |
+--------+------------------+
3 rows in set (0.00 sec)

mysql> delete u from Users as u
    -> left outer join Subscriptionoffering as so
    -> on so.userid = u.userid
    -> where so.userid is null;
Query OK, 2 rows affected (0.36 sec)

mysql> select * from Users;
+--------+
| userid |
+--------+
|      1 |
|      3 |
|      5 |
+--------+
3 rows in set (0.00 sec)
相关问题