我无法理解如何使用子查询从主查询中删除条目。我有两张桌子;
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的内容?
答案 0 :(得分: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);