5

I want to use the WITH syntax inside the SQL query in Zend framework, the SQL looks like this:

WITH t AS
(SELECT item_id, row_number() OVER (ORDER BY some_criteria DESC) rn
   FROM orders)
SELECT t2.rn, t2.item_id
  FROM t t1 JOIN t t2 ON (t2.rn > t1.rn)
 WHERE t1.item_id = 145;

How can I do so in Zend Framework? with Zend_Db_Select? Any Suggestions?

Himanshu
  • 31,810
  • 31
  • 111
  • 133
Capitaine
  • 1,923
  • 6
  • 27
  • 46

3 Answers3

3

With Zend_Db_Select you can't do it in beautiful way, so I suggest you to use simple query:

$q = "WITH t ..."
$db->fetchAll($q);
Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143
0

I quote-

Using Zend_Db_Select is not mandatory. For very simple SELECT queries, it is usually simpler to specify the entire SQL query as a string and execute it using Adapter methods like query() or fetchAll(). Using Zend_Db_Select is helpful if you need to assemble a SELECT query procedurally, or based on conditional logic in your application.

So you can try this

$wthselect = 'WITH t AS
          (SELECT item_id, row_number() OVER (ORDER BY some_criteria DESC) rn
              FROM orders)
         SELECT t2.rn, t2.item_id
           FROM t t1 JOIN t t2 ON (t2.rn > t1.rn)
           WHERE t1.item_id = 145';

$stmt = $select->query($wthselect);
$result = $stmt->fetchAll();
Anjan Biswas
  • 7,746
  • 5
  • 47
  • 77
0

The Zend_Db_Select is usefull if the query is somewhat complicated, with parameters and logic included in your application, as already quoted on another answer. Check this link on the official Zend Framework for detailed description of this insctruction.

Also check this useful link from the Zend Framework community, specially this post. It clearly shows that for small and non complicated queries, as the one you posted, is simpler to use the fetchAll() or query() instructions.

So, my advice, use the fetchAll() or query() for your case.

Yaroslav
  • 6,476
  • 10
  • 48
  • 89