选择不与其他列值一起显示的列

时间:2014-06-24 21:33:54

标签: mysql

我有一个包含两列UIDGID的表,其中存在多对一的GID-UID关系(即每个UID可以出现在具有不同GID的许多行中)。

如果我想获得具有特定GID的所有UID,那很容易

SELECT
  UID
FROM
  MyTable
WHERE
  GID = x

但是,如果我希望所有的UID都有一定的GID呢?我想出了这个:

SELECT
  UID
FROM
  (SELECT
    UID, MAX(GID = x) AS has_gid
  FROM
    MyTable
  GROUP BY
    UID
  ) AS subq
WHERE
  has_gid = 0

我认为这样可行,但对于这样一个简单的声音问题似乎就是这样的黑客攻击。是否有一些明显或更有效的方法可以解决这个问题?

3 个答案:

答案 0 :(得分:0)

您可以使用以下子查询:

SELECT
  UID
FROM
  MyTable
WHERE
  UID 
   NOT IN
   (SELECT
     distinct t.UID
    FROM
      MyTable t
    WHERE
      GID = uid_to_exclude)

但是这个查询可能运行得更快:

SELECT
  t1.UID
FROM
  MyTable t1 
  LEFT JOIN
   (SELECT
     DISTINCT t.UID as UID2
    FROM
      MyTable t
    WHERE
      t.GID = uid_to_exclude) as t2 on t1.uid = t2.uid 

WHERE t2.UID2 IS NULL

答案 1 :(得分:0)

有很多方法可以编写这样的查询,即使用外连接并检查选择空值,但我认为最可读和最有效的查询是使用NOT EXISTS sql函数

SELECT UID 
  FROM MYTABLE
 WHERE NOT EXISTS (
    SELECT * 
      FROM MYTABLE T1
     WHERE T1.UID = MYTABLE.UID
       AND T1.GID = X
 ) 

答案 2 :(得分:-2)

尝试有用的HAVING子句:

SELECT uid
FROM MyTable
HAVING COUNT(gid) > 0
GROUP BY uid