【发布时间】:2017-03-15 10:45:54
【问题描述】:
我有 3 个表创建了论坛组和 group_members 我只想获取那些不属于组成员的组以及用户 ID 当前它正在获取组,如果数据组成员表中不存在组 ID 和用户 ID仅当存在 1 个组成员时才在表中,它会拉起记录。简而言之,我想显示哪些用户未加入的组是我的三个表的表模式
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; ?>
【问题讨论】:
-
使用 NOT IN 代替 NOT EXISTS
-
未捕获异常 'PDOException' 并带有消息 'SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“IN (SELECT * FROM group_members WHERE groups.id = group_members.group_id AND use”附近使用正确的语法
-
您的表格中没有“用户 ID”。
-
@AlexBlex 抱歉现在检查
-
选择查询中不应有==。