2017-06-14 37 views
0

我想編寫一個查詢,該查詢根據多種不同條件選擇記錄,並使用運算符AND和OR。在Postgres中合併AND OR語句

例如,如果我編寫以下查詢,我如何保留前兩個條件(network_id = 1 and payment_plan_id = 77)而不在OR聲明之後重寫它們?

select * from transactions where network_id = 1 and payment_plan_id = 
77 and payment_type = 'Subscription' OR payment_type = 'Renewal' 
+0

除非我誤解你的問題,喲你可以把OR語句括在括號中:'select * from transaction where network_id = 1 and payment_plan_id = 77 and(payment_type ='Subscription'or payment_type ='Renewal')' – RToyo

回答

1

使用IN避免括號混亂

select * from transactions 
where network_id = 1 
and payment_plan_id = 77 
and payment_type IN ('Subscription' , 'Renewal') 
2

使用括號:

select * 
from transactions 
where network_id = 1 and payment_plan_id = 77 and 
     (payment_type = 'Subscription' OR payment_type = 'Renewal') 

或者,更好的是,使用in

select * 
from transactions 
where network_id = 1 and payment_plan_id = 77 and 
     payment_type in ('Subscription', 'Renewal')