Iget来自1个表的数据并检查第二个表中不存在的数据

时间:2017-03-15 10:45:54

标签: php mysql

我有3个表创建了论坛组和group_members我想只获得那些不在组成员中的组以及用户ID当前正在获取组,如果数据组成员表中没有组ID和用户ID只有当一个组成员存在时它才会在表中,它会提取记录。简单来说,我想显示用户尚未加入的节目组是我的两个表格的表格模式

Groups
+----+----------+
| id | name     |
+----+----------+
| 1  | group 1  |
| 2  | group 2  |
| 3  | group 3  |
| 4  | group 4  |
+----+----------+

forums
+------------------+-------------+
| id | title       | group_id    |
+------------------+-------------+
| 1  | test 1      |           2 |
| 2  | test 2      |           3 |
| 3  | test 3      |           2 |
| 4  | test 4      |           3 |
| 5  | test 5      |           2 |
| 6  | test 6      |           4 |
+------------------+-------------+

Group_members
+-----------------+-------------+
| id | user_id  |  group_id    |
+-----------------+-------------+
| 1  | 107       |     2        |
| 2  | 106       |     3        |
+-----------------+-------------+

这是我写的sql

<?php
$sql_grp_chk = $this->db->query("SELECT * FROM groups WHERE NOT EXISTS (SELECT * FROM group_members WHERE groups.id == group_members.group_id)");
foreach($sql_grp_chk->result() as $data_ct):
    $sql_gr_coun = $this->db->query("SELECT groups.*, (SELECT count(group_id) FROM forums WHERE groups.id = forums.group_id) as forumcount FROM groups WHERE groups.id != '".$data_ct->id."' ORDER BY forumcount DESC LIMIT 5");
    foreach($sql_gr_coun->result() as $data_count):
        $sql_follow = $this->db->get_where('group_members', array('group_id' => $data_count->id));
        var_dump($data_count);
?>

<?php endforeach; ?>
<?php endforeach; ?>

1 个答案:

答案 0 :(得分:1)

不确定为什么forums存在,但要选择未与用户关联的所有群组,您可以执行left join

select g.* from groups g
left join group_members m on m.group_id = g.id and m.user_id = :userId
where m.id is null;

修改

按照链接的论坛数量选择前5个组:

select g.*, count(nullif(f.id, 1)) as cnt from groups g
inner join forums f on f.group_id = g.id
group by g.id
order by cnt desc
limit 5;

两个查询在一起 - 前5个组,按链接的论坛数量,哪个用户尚未加入:

select g.*, count(nullif(f.id, 1)) as cnt from groups g
left join group_members m on m.group_id = g.id and m.user_id = :userId
left join forums f on f.group_id = g.id
where m.id is null
group by g.id
order by cnt desc
limit 5;