从结果中排除子集的 CodeIgniter 查询

CodeIgniter query to exclude a subset from results

在完成 JOIN 之后,我在弄清楚如何编写正确的查询时遇到了一些麻烦。我需要获得第 1 组中的所有用户,同时排除这些结果的一个子集。

Table users:

id    name
1     John Smith
2     Joe Blow
3     Mary Jane

Table users_groups:

user_id   group_id
1         1
1         3
1         4
2         1
2         4
2         5
3         1
3         6

第6组的每个人也都在第1组,但是并不是第1组的每个人都在第6组。换句话说,第6组是第1组的子集。

我需要一个查询,该查询将提供第 1 组中所有用户的列表(同时排除第 6 组中的用户)。对于上面的示例,我应该得到两个结果,John SmithJoe Blow

我正在使用 CodeIgniter v3

这是我的尝试(为了清楚起见,我删除了缓存代码)...

$this->db->from('users');

$this->db->select('
    users.id                AS `id`,
    users.name              AS `name`,
    users_groups.group_id   AS `group_id`
', FALSE);

$this->db->join('users_groups', 'users_groups.user_id = users.id', 'LEFT');

$this->db->group_by('users.email'); // remove duplication caused by JOIN

$this->db->where('users_groups.group_id = 1'); // get all users in Group 1

$this->db->where('users_groups.group_id <> 6'); // ignore all users in Group 6

return $this->db->get()->result_array();

我在这里遇到的问题是我总是得到第 1 组用户的完整列表。因为 JOIN 生成所有用户和所有组的列表,其中同一用户被列出多个次,该人所属的每个组都有一个条目。我的查询正在删除第 6 组条目,但这并不好,因为相同的用户也在第 1 组中。

我刚刚解释了我的查询失败的原因,但我仍然不知道如何获得成功。如何获取第 1 组用户,然后删除第 1 组和第 6 组中的用户子集?这些用户也可以在其他组中,但这些应该被忽略...我只想从组 1 的用户列表中排除组 1 和 6 中的用户。

结果中的每个用户:

任何建议表示赞赏。

您需要一个 "not exists" 子句作为过滤器。

And not exists (select 1 from users_groups x where 
x.user_id = users_groups.user_id and group_id = 6

我不熟悉 code ignite,但我确信这是可行的

感谢 ,它正在运行。这是在 CodeIgniter 中的实现方式...

$this->db->where('users_groups.group_id = 1'); // get all users in Group 1

$this->db->where('
    NOT EXISTS (
        SELECT 1 FROM users_groups x 
        WHERE x.user_id = users_groups.user_id AND group_id = 6
    )
');  // exclude users in Group 6