0

在执行JOIN. 我需要获取第 1 组中的所有用户,同时排除这些结果的子集。

users

id    name
1     John Smith
2     Joe Blow
3     Mary Jane

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 Smith并且Joe 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 中的用户。

结果中的每个用户:

  • 必须在第 1 组
  • 不得在第 6 组
  • 可能在也可能不在任何其他组中

任何建议表示赞赏。

4

2 回答 2

1

您需要一个“不存在”子句作为过滤器。

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

我不熟悉代码点燃,但我确定这是可行的

于 2015-06-19T00:45:51.373 回答
0

感谢菲利普的回答,它正在工作。这是如何在 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
于 2015-06-19T00:56:02.863 回答