开发者

Query for existence in HQL efficiently

I have a class Employee with three class members: id, isVisible, sectionId.

I want to query in HQL:

  1. If a certain section has any Employees at all
  2. If so - are all the employees within that section hidden.

Now I am doing something like:

SELECT count(e.id), count(nullif(e.isVisible,0)) 
        from Employee e where sectionId = :sectionId

But counting is not so efficient because it requires a full table scan, and I don't need the number counted.

I can do two queries instead.

Query the section for employees by running a simple select and limiting the number of results to a single result:

SELECT e.id from Employee e where sectionId = :sectionId

And if a result is returned, query for the first employee in the section开发者_JAVA百科 that is visible:

SELECT e.id from Employee e where visible = 1 and sectionId = :sectionId

My question is: Can I do both checks in a single query?


Since you are only interested in getting one row from each query you can full outer join them to get a single row back with two columns. You will need to alias Employee to E1 and E2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜