【问题标题】:sql get all entries from second table when only key from first table is available当只有第一个表中的键可用时,sql 从第二个表中获取所有条目
【发布时间】:2020-10-30 00:03:24
【问题描述】:

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

完成了这个
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对结果进行排序,但是对于页面来说这是必需的,当只有可用的userID而且还按优先级排序结果时,如何获得所有结果?

【问题讨论】:

  • 请向我们展示这两个表的架构
  • 提示:JOIN 表格。

标签: php mysql sql


【解决方案1】:

您可以使用 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 普通代码

【讨论】:

  • 按 ga.groupPriority 排序,请更改,因为更改后我只能编辑超过 6 个字符
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多