Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

Sql performance query multiple conditions on same column

I have a table ORDERS with ORDER_ID and SERVICE_ID field.

I can have multiple entries in table like:

ID   ORDER_ID   SERVICE_ID
1     000001         1
2     000001         2
3     000001         3

4     000002         1
5     000002         2

I need to final all orders that have entries for service_id 2 but not for service_id 3. My query is:

SELECT * FROM ORDERS
WHERE SERVICE_ID = 2
  AND ORDER_ID NOT IN (SELECT ORDER_ID FROM ORDERS WHERE SERVICE_ID = 3) 

Is there another way to do this in order to improve performance?

Thanx

question from:https://stackoverflow.com/questions/65843827/sql-performance-query-multiple-conditions-on-same-column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use NOT EXISTS which generally performs better than NOT IN:

SELECT * FROM ORDERS O
WHERE O.SERVICE_ID = 2
  AND NOT EXISTS 
      (SELECT 1 FROM ORDERS OO WHERE OO.ORDER_ID = O.ORDER_ID AND OO.SERVICE_ID = 3) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...