mysql查询到magento集合或在magento中编写连接子查询

时间:2015-02-18 13:27:05

标签: php magento zend-db

我有一个类似于

的数据库查询
SELECT  f.forum_id,
 t.topic_id,
 MAX(p.post_id) AS `maxpostid`,
 p.admin_user_id,
 p.user_id,
 t2.topicscount,
 SUM(Maxp.postcount) AS postscount,
 CONCAT(au.firstname,' ',au.lastname) AS adminname, 
 fu.nick_name AS nickname,
 CONCAT(ce1.value,' ',ce2.value) AS fullname 

FROM    my_forum AS f        

  LEFT JOIN my_topic AS t
  ON f.forum_id = t.forum_id 

  LEFT JOIN
   (SELECT  topic_id, 
   MAX(post_id) AS post_id,
   COUNT(*) AS postcount
  FROM my_post 
  GROUP BY topic_id
    ) AS Maxp
  ON Maxp.topic_id = t.topic_id 

  LEFT JOIN my_post AS p
  ON p.post_id = Maxp.post_id

  LEFT JOIN admin_user AS au
  ON au.user_id = p.admin_user_id

  LEFT JOIN my_user AS fu
  ON fu.user_id = p.user_id

  LEFT JOIN customer_entity_varchar AS ce1
  ON ce1.entity_id = p.user_id
  AND ce1.attribute_id = 1

  LEFT JOIN customer_entity_varchar AS ce2
  ON ce2.entity_id = p.user_id
  AND ce2.attribute_id = 2

 LEFT JOIN
 (SELECT  forum_id, COUNT(*) AS topicscount
     FROM    my_topic
     GROUP BY forum_id
 ) AS t2
 ON t2.forum_id = f.forum_id

WHERE   forum_status = '1'
GROUP BY f.forum_id

我想用magento集合编写它或将自定义查询转换为集合,是否可能?

我不知道如何编写像

这样的联接
LEFT JOIN
( SELECT  topic_id, 
    MAX(post_id) AS post_id,
    COUNT(*) AS postcount
  FROM my_post 
  GROUP BY topic_id
) AS Maxp
    ON Maxp.topic_id = t.topic_id 

在magento, 因为magento写连接为

$col->getSelect()->join(array('t'  => 'topic'),'main_f.forum_id = t.forum_id');

如何用子查询编写它?

由于

2 个答案:

答案 0 :(得分:1)

在Magento2中,将子查询写为

$subquery = new \Zend_Db_Expr('SELECT my_post.topic_id, MAX(my_post.post_id) AS post_id, COUNT(*) AS postcount FROM my_post GROUP BY my_post.topic_id');
$sql = $collection->getSelect()->from(array('f'  => 'my_forum'), array('f.forum_id'));
$sql->columns(array('Maxp' => $subquery));
//to debug
$sql->__toString();exit;

答案 1 :(得分:0)

我没有测试过这段代码,但它应该是这样的:

$subquery = new Zend_Db_Expr('SELECT my_post.topic_id, MAX(my_post.post_id) AS post_id, COUNT(*) AS postcount FROM my_post GROUP BY my_post.topic_id');
$collection->getSelect()->joinLeft(array('t'  => 'topic'), 'Maxp.topic_id = t.topic_id', array('Maxp' => $subquery));