Mysql选择,我如何找到具有在同一列中给出的值的应用程序名称

时间:2012-12-18 05:43:46

标签: mysql

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

的应用程序
name   permissions
app1    perm1
app1    perm5
app1    perm6
app2    perm1
app2    perm8
app3    perm1
app3    perm6
app3    perm2
app3    perm4

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

2 个答案:

答案 0 :(得分:2)

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

OR

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

答案 1 :(得分: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.(我们处理的情况是通过在IFNULL函数中包装t.permissions来获取NULL。)

如果我们找到'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