我需要选择用户表中存在的记录,但表 groups_members,groups_members_unapproved 和 groups_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');
答案 0 :(得分:1)
最简单的方法就是将???
留在子查询中,因为那里不需要它们;
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')
答案 1 :(得分:0)
你可能要做的是像这样的左外联接
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,但是where子句中的* IS NULL
行将这些记录限制为仅存在的情况不匹配用户表和任何其他表之间的成员ID。
我不太确定groupid
在您的查询中带来了什么价值。我认为,如果您担心在用户级别识别记录,那么过滤它将是一个不必要的字段。
这应该是比使用子选择更有效的查询,只要您的所有ID字段都被编入索引。当然,如果这是您希望经常执行的查询,您可能需要考虑更改架构以获得更优化的查询。