首页 > 解决方案 > 当只有第一个表中的键可用时,sql 从第二个表中获取所有条目

问题描述

用户也应该能够看到他有权访问的组。我用

TABLE1 groupaccess
userID | groupID
==============
 2     |    4
 2     |    5
...

TABLE2 groups
groupID | groupName | groupPriority
==================================
 1      | Group 1   |    11
 2      | Group 2   |    100
 3      | Group 3   |    600
...

我当前的 php 查询如下所示:

public function sqlGetGroups() {
    $groupIDs = $this->mysqliSelectPrepared("SELECT groupID FROM groupaccess WHERE userID = ?", $_SESSION['userID']);
    foreach ($groupIDs as $groupID) {
        $group = $this->mysqliSelectPrepared("SELECT * FROM groups WHERE ID = ?", $groupID);
        $groups[] = $group;
    }
    return $groups;
}

目前我无法按 groupPriority 对结果进行排序,但是对于页面来说这是必需的,当只有用户 ID 可用但还按优先级排序结果时,如何获得所有结果?

标签: phpmysqlsql

解决方案


您可以使用 JOIN 在一个查询中执行此操作

SELECT g.* 
FROM groups g
    LEFT JOIN groupaccess ga ON g.groupID = ga.groupID
    AND ga.userID = 2
ORDER BY ga.groupPriority;

请记住,mysqliSelectPrepared()如果您希望在答案中可靠地使用非 PHP vanilla 代码,则需要在问题中显示


推荐阅读