dreamwind1985
2017-11-05 07:59
浏览 58
已采纳

子查询成为Magento中Mysql查询中的列

I have a query in Magento ($Collection) in which I joined a table to have the result I wanted.

This is my $Collection

protected function _prepareCollection()
{
    $collection = Mage::getResourceModel($this->_getCollectionClass());
    $stmp = "(SELECT GROUP_CONCAT(comment SEPARATOR '----' ) FROM mgmx_sales_flat_invoice_comment a WHERE a.parent_id = `main_table`.`entity_id` group by parent_id)";
    $collection->getSelect()->join( array('a'=> mgmx_sales_flat_invoice_comment), 'a.parent_id = main_table.entity_id', $stmp);


    $this->setCollection($collection);
    echo $collection->getSelect();die();
    return parent::_prepareCollection();
}

This $Collection, if you notice I echoed it. It will print this Query.

SELECT 
     `main_table`.*, 
           (SELECT 
                  GROUP_CONCAT
                  (comment SEPARATOR '----' ) 
            FROM 
                  mgmx_sales_flat_invoice_comment a 
            WHERE 
                  a.parent_id = main_table`.`entity_id 
            GROUP BY 
                  parent_id)
  FROM 
      `mgmx_sales_flat_invoice_grid` 
   AS 
      `main_table` 
   INNER JOIN 
       `mgmx_sales_flat_invoice_comment` 
   AS 
       `a` 
    ON 
         a.parent_id = main_table.entity_id

This Query, on the other hand is working if I can remove some of the "things" in it like '`' so it will function normally.

Here's what will happen Step by Step.

  1. Upon running the query in Mysql it will return an error

1054 - Unknown column '(SELECT GROUP_CONCAT(comment SEPARATOR '----' ) FROM mgmx_sales_flat_invoice_comment a WHERE a.parent_id = main_table.entity_id group by parent_id)' in 'field list'

if I remove the `` before and after the (SELECT statement) like the one below

SELECT `main_table`.*, 
    (SELECT 
            GROUP_CONCAT(comment SEPARATOR '----' ) 
     FROM 
            mgmx_sales_flat_invoice_comment a
     WHERE a.parent_id = main_table`.`entity_id 
     group by parent_id) 
FROM `mgmx_sales_flat_invoice_grid` 
AS `main_table`
INNER JOIN `mgmx_sales_flat_invoice_comment` 
AS `a` ON a.parent_id = main_table.entity_id

It will show this error instead

right syntax to use near '.entity_id group by parent_id) FROM mgmx_sales_flat_invoice_grid AS `main_ta' at line 1

because of this

WHERE a.parent_id = main_table`.`entity_id 

how do I remove that `` and how do I group by the final $collection Query.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题