0

我需要选择存在于users表中但不存在于表groups_members、groups_members_unapprovedgroups_invitations中的记录。

$_POST['msg_id']包含多个用户 ID,我不知道如何在 3 个子查询中使用implode语句,所以我将其替换为 ??? - 问号。

谢谢。

$result = mysql_query("SELECT id FROM users
WHERE id IN (". implode(', ', $_POST['msg_id']).")
AND id NOT IN (SELECT memberid FROM groups_members where memberid='???' and groupid='$cid')
AND id NOT IN (SELECT memberid FROM groups_members_unapproved where memberid='???' and groupid='$cid')
AND id NOT IN (SELECT invited FROM groups_invitations where invited = '???' and groupid='$cid')",$gb1) or die('Error');
4

2 回答 2

1

最简单的方法是把???out 留在子查询中,因为那里不需要它们;

SELECT id FROM users WHERE id IN (...)
AND id NOT IN 
  (SELECT memberid FROM groups_members WHERE groupid='$cid')
AND id NOT IN 
  (SELECT memberid FROM groups_members_unapproved WHERE groupid='$cid')
AND id NOT IN 
  (SELECT invited FROM groups_invitations WHERE groupid='$cid')

SQLfiddle 演示

于 2012-10-23T17:31:21.327 回答
0

您可能想要做的是这样的 LEFT OUTER JOIN

SELECT id FROM users AS u
LEFT OUTER JOIN groups_members AS gm ON u.id = gm.memberid
LEFT OUTER JOIN groups_members_unapproved AS gmu ON u.id = gmu.memberid
LEFT OUTER JOIN groups_invitations AS gi ON u.id = gi.invited
WHERE
id IN (<your implode here>)
AND gm.memberid IS NULL
AND gmu.memberid IS NULL
AND gi.invited IS NULL
AND gm.groupid <> <your group id>
AND gmu.groupid <> <your group id>
AND gi.groupid <> <your group id>

这里的想法是,即使没有匹配的 id,外连接也会返回所有连接表中的记录,但是* IS NULLwhere 子句中的行会将这些记录限制为仅在用户表之间没有匹配的成员 id 的情况下和任何其他表。

我不太确定groupid您的查询带来了什么价值。我认为,如果您关心在用户级别识别记录,那将是一个不必要的过滤字段。

这应该是比使用子选择更有效的查询,只要您的所有 ID 字段都被索引。当然,如果这是您希望经常执行的查询,您可能需要考虑更改架构以获得更优化的查询。

于 2012-10-23T17:33:15.593 回答