0

我有一个表,其中包含应用程序名称和授予应用程序的权限。我需要找到需要这两者的应用程序

name   permissions
app1    perm1
app1    perm5
app1    perm6
app2    perm1
app2    perm8
app3    perm1
app3    perm6
app3    perm2
app3    perm4

我如何找到同时具有“perm1 和 perm6”的应用程序名称......?

4

2 回答 2

2
SELECT name
FROM tableName
WHERE   permissions IN ('perm1','perm6')
GROUP BY name
HAVING COUNT(*) = 2

或者

SELECT name
FROM tableName
WHERE   permissions IN ('perm1','perm6')
GROUP BY name
HAVING COUNT(DISTINCT permissions) = 2
于 2012-12-18T05:45:27.120 回答
1

这是一种方法。

SELECT t.name
  FROM mytable t
 GROUP BY t.name
HAVING MAX(IFNULL(t.permissions,'')='perm1')
     + MAX(IFNULL(t.permissions,'')='perm6') = 2
 ORDER BY t.name

我们正在使用 GROUP BY 和聚合函数,如果我们找到具有 'perm1' 的行,则 t.permissons='perm1' 返回 1,否则返回 0。(我们通过以下方式处理 NULL 的情况将 t.permissions 包装在 IFNULL 函数中。)

如果我们同时找到“perm1”和“perm6”,则 HAVING 谓词将评估为 TRUE,并且将返回该行。


另一种方法是使用 EXISTS 谓词运行相关子查询:

SELECT t.name
  FROM mytable t
 WHERE t.permissions = 'perm1'
   AND EXISTS 
       ( SELECT 1 
           FROM mytable s
          WHERE s.name = t.name
            AND s.permissions = 'perm6'
       )
 GROUP BY t.name
 ORDER BY t.name

或等价物,使用 IN 谓词:

 SELECT t.name
   FROM mytable t
  WHERE t.permissions = 'perm1'
    AND t.name IN 
        ( SELECT s.name
            FROM mytable s
           WHERE s.permissions = 'perm6'
             AND s.name IS NOT NULL
           GROUP BY s.name
        )
  GROUP BY t.name
  ORDER BY t.name

第四种方法是:

 SELECT t.name
   FROM mytable t
   JOIN mytable s
     ON t.name = s.name
    AND t.permissions = 'perm1'
    AND s.permissions = 'perm6'
  GROUP BY t.name
  ORDER BY t.name
于 2012-12-18T06:24:56.667 回答