php - 当只有第一个表中的键可用时,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 可用但还按优先级排序结果时,如何获得所有结果?
解决方案
您可以使用 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 代码,则需要在问题中显示
推荐阅读
- python - 从 Python 的列表中为现有文件的每一行添加一个额外的字母
- vert.x - vertx.executeBlocking 失败
- php - 如何在数组中添加字符串?
- django - django runserver 找不到静态文件,但是远程服务器可以
- powershell - 如何在 cmd /c 中设置 %ERRORLEVEL%?
- vb.net - 无法创建 Microsoft.VisualBasic.Logging.FileLogTraceListener,Microsoft.VisualBasic / 找不到路径的一部分
- android - 应用程序可以在不转到 Wifi 设置的情况下将手机/智能手机连接到 Wifi 网络吗?
- javascript - Chome 浏览器 onbeforeunload 事件无法显示警告弹出窗口,但如果我们打开 chrome 开发工具,则可以正常工作
- powershell - 如何在 PowerShell 中用连续数字重命名每个 .jpg 文件名
- bash - 基于 C++ 二进制运行时参数创建 Bash 脚本文件名