排除具有相关值的行

时间:2013-05-26 15:53:50

标签: mysql

假设我有一张如下表:

++++++++++++++++++++++++++++++++++++++++
  url        | fieldname    | value
++++++++++++++++++++++++++++++++++++++++
  a,b,c      | RATE         | 45
----------------------------------------
  a,b,c      | PLAY         | 5
----------------------------------------
  a,b,c      | DATE         | 2013-05-20
----------------------------------------
  d,e,f      | PLAY         | 2
----------------------------------------
  d,e,f      | DATE         | 2013-01-01
++++++++++++++++++++++++++++++++++++++++

如何在url列中排除具有一个特定(未知!)值的所有行,如果其中一个具有相同url值的行在其中具有特定(已知!)值fieldname列?

例如,如果我想在RATE中排除fieldname行,而且排除“相关”行(url中具有相同值的行,该怎么办?列) - 这样它会返回一个这样的表?:

++++++++++++++++++++++++++++++++++++++++
  url        | fieldname    | value
++++++++++++++++++++++++++++++++++++++++
  d,e,f      | PLAY         | 2
----------------------------------------
  d,e,f      | DATE         | 2013-01-01
++++++++++++++++++++++++++++++++++++++++

同样,请记住,不应在查询中指定url值。

1 个答案:

答案 0 :(得分:1)

这是“sets-within-sets”查询的示例。我喜欢使用having子句进行聚合,因为它是最通用的方法。

以下查询获取您感兴趣的网址:

select url
from t
group by url
having sum(case when fieldname = 'RATE' then 1 else 0 end) = 0;

要获取原始表中的所有行,您需要重新加入它:

select t.*
from t join
     (select url
      from t
      group by url
      having sum(case when fieldname = 'RATE' then 1 else 0 end) = 0
     ) turl
     on t.url = turl.url