Oracle-11g-R2

使用不返回所需結果集的“邏輯運算符 (AND)”進行查詢

  • July 4, 2020

我有一張桌子:

create table test_table
(customer_num  NUMBER,
dep_group     VARCHAR2(50),
dep_type      VARCHAR2(50),
balance       NUMBER)

該表有兩條記錄:

                 " test_table "
--------------------------------------------------  
customer_num   dep_group   dep_type    balance       
    1            x           x1          10
    1            x           x2          10

下面的查詢必須返回表的兩條記錄,但它沒有,這很奇怪!

select *
from test_table
where ((dep_group = 'x') AND (dep_type = 'x1') AND ((balance) > 1)
  
          AND
  
    ((dep_group = 'x') AND (dep_type = 'x2') AND ((balance) > 1)))

當我分別執行查詢的每個部分時,它給了我想要的記錄

Q1:
select *
from test_tablet t
where (dep_group = 'x') AND (dep_type = 'x1') AND ((balance) > 1) 

Q2:
select *
from test_tablet t
where (dep_group = 'x') AND (dep_type = 'x2') AND ((balance) > 1) 

我的意思是customer = 1同時匹配兩個條件,原始查詢必須給我表的兩條記錄。我的查詢或我對邏輯運算符的理解有問題嗎?

提前致謝。

正如 Mustaccio 在評論中提到的那樣,您想要的行dev_type'x1' or 'x2',而不是'x1' and 'x2'

此外,您只需要圍繞每個替代條件集的括號。其他人甚麼也沒做,他們只是感到困惑。

with test_table (customer_num, dep_group, dep_type, balance) as
    ( select 1, 'x', 'x1', 10 from dual union all
      select 1, 'x', 'x2', 10 from dual
    )
select *
from  test_table
where (dep_group = 'x' and dep_type = 'x1' and balance > 1)
or    (dep_group = 'x' and dep_type = 'x2' and balance > 1)

引用自:https://dba.stackexchange.com/questions/267907