views:

77

answers:

1

I'd like to do a single query on one table without using UNION

Here are the two queries that I need to combine.

SELECT field1, field2, field3 FROM table1 WHERE field4 != 'condition1' AND feild3 >= 'condition2' ORDER BY field3 ASC LIMIT 20;
SELECT field1, field2, field3 FROM table1 WHERE field4 != 'condition1' AND feild3 < 'condition2' ORDER BY field3 DESC LIMIT 5;

Basically, I'm trying to get 20 records above a certain record (ordered by field3, not the id), and 5 records below it, without grabbing the record itself in the results.

The trick is, I can't use UNION.

+1  A: 

You could do something like the following -

select a.*, b.*
from (select field1, field2, field3 
      from table1 
      where field4 != 'condition1' 
        and feild3 >= 'condition2' 
      order by field3 ASC 
      limit 20) a, 
     (select field1, field2, field3 
      from table1 
      where field4 != 'condition1' 
        and feild3 < 'condition2' 
      order my field3 desc
      limit 5) b
lee-m
Aren't you joining subquery `a` and subquery `b` without condition? This would return a lot more rows than expected.
Peter Lang
This looks good.Using subqueries in cakePHP is difficult work. I wanted to avoid using $this->Model->query, but oh well.
Stephen