是否有可能减少重复的子查询查找?

时间:2017-11-12 23:03:41

标签: mysql sql

我试图将此作为单个查询运行,但由于重复的子查询仅执行一次,我认为可能使用JOIN子句但我不确定它是否可行,因为我正在查找名称和同一行的角色字段3次?我能想到的唯一方法是从我的代码执行一次子查询,以获取角色和名称值以注入此主查询。

SELECT id, isActive, role
FROM accountMembers
WHERE account=:acc
AND isActive=true
AND (
        (
            name > (SELECT name FROM accountMembers WHERE account=:acc AND id =:id)
            AND role = (SELECT role FROM accountMembers WHERE account=:acc AND id =:id)
        )
        OR role > (SELECT role FROM accountMembers WHERE account=:acc AND id =:id)
)
ORDER BY role ASC, name ASC LIMIT :lim

2 个答案:

答案 0 :(得分:1)

MySQL支持元组比较:

SELECT am.*
FROM accountMembers am
WHERE am.account = :acc and
      am.isActive = true and
      (am.role, am.name) > (select am2.role, am2.name
                            from accountMembers am2
                            where am2.account = :acc AND am2.id =:id
                           );

即使没有,您也可以将逻辑移到from子句:

SELECT am.*
FROM accountMembers am JOIN
     ON am2.account = :acc AND am2.id =:id

WHERE am.account = :acc and
      am.isActive = true and
      (am.role > am2.role or
       am.role = am2.role and am.name > am2.name
      );

答案 1 :(得分:0)

答案是只使用第二个别名将from表中的表包含两次,以区分这两个,然后包含其他约束,如下所示:

SELECT a1.id, a1.isActive, a1.role
FROM accountMembers a1, accountMembers a2
WHERE a1.account=:acc
AND a1.isActive=true
AND a2.account=:acc
AND a2.id=:id
AND (
        (
            a1.name > a2.name
            AND a1.role = a2.role
        )
        OR a1.role > a2.role
)
ORDER BY a1.role ASC, a1.name ASC LIMIT :lim