2

I am trying to do a query of the form:

SELECT TableA.id, TableB.id 
FROM TableA
INNER JOIN TableB ON TableB.a_id = TableA.id 
WHERE
TableB.field1 = ( SELECT TableB.field1 FROM TableB WHERE TableB.a_id=TableA.id ORDER BY TableB.created_at DESC LIMIT 1 )
GROUP BY TableA.id, TableB.field1 ORDER BY TableA.id ASC

the important thing being that the where clause has a subquery.

My question is, how would you use addFieldToFilter() or even ZendDB functions to implement the subquery?

asked Jul 1, 2013 at 19:47

2 Answers 2

4

You would use Zend_Db_Expr - which can take either another collection object, an explicit SQL statement, or a fragment of a statement. :

$collection->getSelect()->where('TableB.field1 = (?)', new Zend_Db_Expr($subquery->__toString());

Here, $subquery is another collection but could easily just be the text as you stated, SELECT TableB.field1 FROM TableB WHERE TableB.a_id=TableA.id ORDER BY TableB.created_at DESC LIMIT 1

answered Jul 1, 2013 at 20:04
3
  • Does this break later attempts to use addFieldToFilter? Commented Jul 1, 2013 at 20:38
  • Not in my experience, no. In core they do these calls successively -- I've seen Zend_Db_Expr used in column definition, e.g. in the SELECT part of the query. Commented Jul 1, 2013 at 20:48
  • It's tough to show some really great examples because they're in Enterprise Edition... Commented Jul 1, 2013 at 20:49
2

You can check this example in the magento source code: Mage_Sales_Model_Resource_Report_Bestsellers::aggregate

search for 'subSelect': http://www.magentodocs.org/1.7.0.2/d1/d51/_sales_2_model_2_resource_2_report_2_bestsellers_8php_source.php

More examples you can find in the Mage_Sales_Model_Resource_Report_* classes.

answered Jul 2, 2013 at 10:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.