如何根据其他行中的列值进行过滤?

时间:2015-12-07 17:54:23

标签: mysql sql

我不知道如何更好地说出标题问题。

以下是示例表:

| email | subscription ref num |  state   |
|-------|----------------------|----------|
| 1@1.1 |         10           | inactive |
| 2@2.2 |         11           | inactive |
| 1@1.1 |         12           | inactive |
| 1@1.1 |         13           |  active  |
| 3@3.3 |         14           |  active  |
etc

我想从表中收到所有没有有效订阅的电子邮件。我无法过滤WHERE state=inactve,因为请查看电子邮件地址1@1.1。该用户既有旧的非活动订阅,也有当前活动的订阅。

因此,对于此示例数据库,我只想返回电子邮件2@2.2。希望有道理。

有人可以帮助我使用正确的查询吗?

5 个答案:

答案 0 :(得分:4)

...没有有效订阅:

select distinct email
from yourTable
where email not in 
     (select email from yourTable where state = 'active')

查询解释了自己:选择任何行中没有活动状态的不同电子邮件。

ADDED:您可以在mySql中的state列上创建索引。此外,这可能会更快:

select distinct email
from yourTable
where not exists 
     (select * from yourTable as helper 
      where state = 'active' and helper.email = yourTable.email )

答案 1 :(得分:2)

这是单程......

select email 
from sampletable 
group by email
having max(state) = 'inactive' and min(state) = 'inactive'

答案 2 :(得分:0)

使用Having子句过滤组。试试这个

select email 
from yourtable 
group by email
having count(case when state ='inactive' then 1 end) = 1 
   and count(*)= 1

SQLFIDDLE DEMO

答案 3 :(得分:0)

SELECT DISTINCT x.* 
           FROM my_table x 
           LEFT 
           JOIN my_table y 
             ON y.email = x.email 
            AND y.state = 'active' 
          WHERE y.id IS NULL;

答案 4 :(得分:0)

select email 
from table
group by email
having max(state) = 'inactive' 
  and count(distinct state) = 1

或没有分组

select t1.email
from table t1
where t1.state = 'inactive'
  and not exists(
    select 1
    from table t2
    where t2.email = t1.email
      and t2.status = 'active'
  )