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
90 views
in Technique[技术] by (71.8m points)

sql - I can’t figure out how to improve this query

I have this really huge table with several million records in it. And I would like to create a query with multiple where conditions on the same field.

I need to know how many employees have access to building A, but not to building B. Supposedly, any employee with access to building A should have access granted to building B, so I’m looking for anomalies.

So far, the best I’ve come up with is this:

select employee_id from personnel where building = A
minus
select employee_id from personnel where building = B;

But I’m pretty sure there must be a quicker and more efficent way to do this. Maybe some sort of subquery?

Thanks in advance.

question from:https://stackoverflow.com/questions/66068004/i-can-t-figure-out-how-to-improve-this-query

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

1 Reply

0 votes
by (71.8m points)

You can try one of the following:

select employee
from personnel
where building in (A, B)
having max(building) = min(building) and min(building) = A;

or:

select employee
from personnel
where building = A and
      not exists (select 1
                  from personnel p2
                  where p2.employee = p.employee and p2.building = B
                 );

In particular, this can use indexes on personnel(building, employee) and personnel(employee, building).


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

...