3

我无法理解如何使用子查询从主查询中删除条目。我有两张桌子;

mysql> select userid, username, firstname, lastname from users_accounts where (userid = 7) or (userid = 8);

+--------+----------+-----------+----------+
| userid | username | firstname | lastname |
+--------+----------+-----------+----------+
|      7 | csmith   | Chris     | Smith    |
|      8 | dsmith   | Dan       | Smith    |
+--------+----------+-----------+----------+
2 rows in set (0.00 sec)

mysql> select * from users_contacts where (userid = 7) or (userid = 8);
+---------+--------+-----------+-----------+---------------------+
| tableid | userid | contactid | confirmed | timestamp           |
+---------+--------+-----------+-----------+---------------------+
|       4 |      7 |         7 |         0 | 2013-10-03 12:34:24 |
|       6 |      8 |         8 |         0 | 2013-10-04 09:05:00 |
|       7 |      7 |         8 |         1 | 2013-10-04 09:08:20 |
+---------+--------+-----------+-----------+---------------------+
3 rows in set (0.00 sec)

我想做的是从 users_accounts 表中提取联系人列表;

1)省略用户自己的账号(换句话说,我不想在列表中看到自己的名字)。

2) 查看所有“已确认”状态为“0”的联系人,但

3) 如果联系人的“已确认”状态也恰好是“1”(请求已发送)或“2”(请求已确认),则不要将它们包含在结果中。

如何编写子查询来提取任何出现为 1 或 2 的内容?

4

1 回答 1

2

此时的子查询看起来没有必要。您可以像这样加入表格:

select u.userid, u., firstname, u.lastname from users_accounts u join user_contacts c on u.userid = c.userid where u.userid != your_user_id and c.confirmed = 0;

在这个通用示例中,your_user_id显然是一个占位符,用于确定当前用户的 ID。但如果你绝对必须使用子查询:

select userid, username, firstname, lastname from users_accounts where userid != your_user_id and userid not in (select userid from user_contacts where confirmed = 1 or confirmed = 2);
于 2013-10-04T16:37:15.690 回答