簡體   English   中英

如何根據其他行中的列值進行過濾?

[英]How to filter based on column values in other rows?

我不知道寫標題問題的更好方法。

這是示例表:

| 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 希望有道理。

有人可以幫助我使用正確的查詢嗎?

...沒有有效的訂閱:

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

查詢會自我解釋:選擇在任何行中都沒有活動狀態的不同電子郵件。

添加:您可以在mySql的狀態列上創建索引。 此外,這可能會更快:

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

這是一種方法

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

使用Having子句來過濾組。 嘗試這個

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

SQLFIDDLE演示

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;
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'
  )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM