从表中获取用户,其中组=另一条表行的组,但我具有另一条表行的ID

时间:2018-08-17 16:49:55

标签: php mysql pdo

我的用户列表:

enter image description here

GROUP_PERMISSIONS表

enter image description here

问题:

我如何从组中获取所有用户(从用户表中),即等于groups_permissions表中的组,但我从groups_permissions表中获得组的 gid

代码:(我已经尝试过(它还具有其他一些功能))

$stmt = $db_con->query("SELECT gp.*, s.*, uu.*, ug.* FROM (SELECT * FROM groups_permissions WHERE gid={$_POST['gp_row_id']}) gp, (SELECT * FROM settings WHERE id='1') s, (SELECT username FROM users ORDER BY id) uu, (SELECT username FROM users WHERE `group`=gp.group_name WHERE gp.gid={$_POST['gp_row_id']}) ug");            
$stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    /* FROM GROUP_PERMISSIONS TABLE */
        $response['id'] = $row['gid'];
        $response['group'] = $row['group_name'];
        $response['restricted_pages'] = $row['restricted_pages'];
        $response['restricted_permissions'] = $row['restricted_permissions'];
    /* FROM SETTINGS TABLE */
        $response['site_pages'] = $row['site_pages'];
        $response['site_permissions'] = $row['site_permissions'];
    /* FROM USERS TABLE */
        $active_ids[]= $row['username'];
        $userlist = join(",", $active_ids);
        $string = trim($userlist,'"');
        $response['users'] = $string;
    }
    echo json_encode($response);

示例 如果在提交表单时,我从groups_permissions获取了一组dsf的行ID 5(请参见上图),那么我想从用户表中获取所有具有组dsf的用户,但由于我具有ID然后从groups_permissions表中选择组,我不知道该使用什么,但是像Select username from users WHERE group='dsf' from permissions_table but rather select the group by the help of gid

1 个答案:

答案 0 :(得分:0)

如果我做对了,选择应该是

"SELECT *
FROM users
INNER JOIN permissions_table ON permissions_table.group_name = users.group
WHERE permissions_table.gid = {$_POST['gp_row_id']}"

我建议将组ID而不是组名保留在用户表中,因为这是关系数据库的正确做法。