簡體   English   中英

如何在SELECT查詢中建立條件以僅過濾出B或不過濾出B和A?

[英]How to make a condition in SELECT query to filter out only B or not B and A?

我有一張桌子

col1     col2
nameA    A
nameA    B
nameB    A
nameC    B
..........

我想在此查詢中創建一個條件:

select *
from tableA
where ....?

要返回所有值(col1中名稱A的col2中值B)或col1中nameA的col2中沒有值 A或B)。 這可能嗎?

預期結果(例如):

col1     col2
nameA    B

col1    col2

使用此查詢

select *
from   tableA
where  col2 = 'B' and col1 = 'nameA'
union all
select *
from   tableA
where  col2 not in ('B','A')
and    col1 = 'nameA'

沒有工會,您可以使用此

select *
from   tableA
where  col1 = 'nameA' 
and (col2='B' or col2!='A')

如果來自Andrews答案的兩個查詢均正確,則可以像這樣合並它們

select *
from   tableA
where  col2 = 'B' 
and    col1 = 'nameA'

union all

select *
from   tableA
where  col2 not in ('B','A')
and    col1 = 'nameA'

嘗試這個

select *
from tableA
where (col1 = 'nameA' and col2 = 'B') 
or (col1= 'nameA' and (col2 is not 'B' and col2 is not 'A'))

具有EXISTS:

select t.* from tablename t
where t.col2 = 'B'
and exists (
  select 1 from tablename
  where col1 = t.col1 and col2 = 'A'
)

暫無
暫無

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

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