让我首先给你一张我的 mysql 查询中使用的表之间的关系图:
(来源:r717.net)
我有一个看起来像这样的查询:
SELECT *
FROM `permissions`
WHERE `id` IN (
SELECT pr.perm_id
FROM `user_roles` as ur
LEFT JOIN `permissions_role` as pr
ON ur.role_id = pr.role_id
WHERE ur.user_id = '$userid'
)
OR `id` IN (
SELECT `perm_id`
FROM `permissions_user`
WHERE `user_id` = '$userid'
)
$userid
是当前用户的用户表中的 id。我将结果中的权限名称存储到一个数组中,该数组表示根据他/她的角色和他/她的 id 分配给用户的所有权限:
<?php
$user_perms = array();
if(mysql_num_rows($query) > 0):
while($result = mysql_fetch_array($query):
$user_perms[] = $result('name');
endwhile;
endif;
?>
print_r($user_perms);
产生如下所示的输出:
Array (
[0] => ACCESS_TELEPHONELIST_PAGE
[1] => ACCESS_VACATIONSCHED_PAGE
[2] => ACCESS_TOURSCHED_PAGE
[3] => ACCESS_WORKSCHED_PAGE
[4] => ACCESS_RESOURCES_LINKS
[5] => ACCESS_PMTOOL_PAGE
[6] => ACCESS_TOOLSTOOL_PAGE
[7] => ACCESS_SHOPTOOLLIST_PAGE
[8] => ACCESS_TOOLINVENTORY_PAGE
[9] => ACCESS_MANAGETOOLLIST_PAGE
[10] => ACCESS_TOOLREPORTS_PAGE
[11] => ACCESS_JOBSLIST_LINKS
[12] => MAIN_TAB_TOOLSTOOL
[13] => ADMIN_TAB_PODMANAGEMENT
[14] => TOOL_TAB_SHOPTOOLLIST
)
我想要做的是将所有用户的角色也存储到另一个数组中,而无需进行第二次查询。我想我需要为子查询使用别名,所以我尝试了这个查询:
SELECT permissions.*, usersroles.role_id
FROM `permissions`
INNER JOIN (
SELECT ur.user_id, pr.perm_id, ur.role_id
FROM `user_roles` as ur
LEFT JOIN `permissions_role` as pr
ON ur.role_id = pr.role_id
WHERE ur.user_id = '$userid'
) AS usersroles ON usersroles.perm_id = permissions.id
INNER JOIN (
SELECT `perm_id`, `user_id`
FROM `permissions_user`
WHERE `user_id` = '$userid'
) AS userperms ON userperms.user_id = usersroles.user_id
AND userperms.perm_id = permissions.id
并且,使用类似于上面代码的代码......
<?php
$user_perms = array();
$user_roles = array();
if(mysql_num_rows($query) > 0):
while($result = mysql_fetch_array($query):
$user_perms = $result('name');
$user_roles = $result('role_id');
endwhile;
endif;
?>
...我收到此警告:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
但是,我想print_r($user_roles);
生成一个如下所示的输出:
Array (
[0] => administrator
[1] => humanresources
[2] => podmanager
)
谁能告诉我我做错了什么,或者建议一种更好的方法将我需要的数据从一个查询中获取到2 个数组中?
编辑:经过仔细考虑,我将代码更改为使用 ImreL 建议的 2 个查询。生成的代码运行良好且执行迅速。我编辑了答案以显示我使用的最终代码,并添加了支持代码以演示我如何使用这 2 个查询。非常感谢 ImreL!