如何选择具有更多条件的用户

时间:2015-11-12 15:35:41

标签: php mysql database medoo

我有一个数据库模型,它将用户存储在组中,并为每个组存储其他权限。结构显示在图像上。

How tables looks

我想创建一个SELECT查询,该查询返回具有一项或多项权限的用户。

我正在使用medoo

public function selUserByRight($rightID)
    {

        return $this->db->select(
            "Users",
            [
                "[>]GroupRight" => ["FK_Group" => "FK_Group"],
                "[>]Rights" => ["GroupRight.FK_Right" => "ID"]
            ],
            [
                "Users.ID","Users.Name","Rights.ID(RightID)","Rights.Right"
            ],
            [
                "AND" =>
                    [
                        "Rights.ID" => $rightID
                    ]
            ]
        );
    }

用法:

$result = $db->selUserByRight(1,2,3);

原始查询:

SELECT "Users"."ID","Users"."Name","Rights"."ID" 
AS "RightID","Rights"."Right" 
FROM "Users" 
LEFT JOIN "GroupRight" ON "Users"."FK_Group" = "GroupRight"."FK_Group" 
LEFT JOIN "Right" ON "GroupRight"."FK_Right" = "Rights"."ID"
WHERE "Rights"."ID = 1

问题是,该查询返回所有用户,但我想只返回user1(因为只有这个用户拥有所有漫游权限)。

有没有解决方案?

1 个答案:

答案 0 :(得分:1)

我认为您可以尝试以下方法:

SELECT dd.ID, dd.Name, dd.FK_Group, _aa.total_rights
FROM (
    SELECT aa.ID, COUNT(*) AS total_rights
    FROM Users AS aa
    INNER JOIN Groups AS bb
    ON aa.FK_Group = bb.ID
    INNER JOIN GroupRight AS cc
    ON bb.ID = cc.FK_Group
    GROUP BY aa.ID
    HAVING COUNT(*) > 0
) AS _aa
INNER JOIN Users AS dd
ON dd.ID = _aa.ID
ORDER BY _aa.total_rights;