将Raw SQL转换为Zend_Db_Select

时间:2014-09-14 20:44:45

标签: mysql magento zend-db-select

我需要将此sql查询转换为Zend_Db_Select对象

'SELECT `main_table`.*, `product_name_table`.`name` as `product_name`, `product_price_table`.`price` as `product_price`,
    COUNT(main_table.answer_id) AS `answer_count`, 
    (SELECT CONCAT(main_table.answer_title, ":::", GROUP_CONCAT(DISTINCT main_table.query SEPARATOR "###"))) AS `answer_title_with_query` 
FROM `nanorepwidgets_answer` AS `main_table`
LEFT JOIN (SELECT `e`.`entity_id`, `at_name`.`value` AS `name` 
        FROM `catalog_product_entity` AS `e` 
        INNER JOIN `catalog_product_entity_varchar` AS `at_name` 
            ON (`at_name`.`entity_id` = `e`.`entity_id`) 
            AND (`at_name`.`attribute_id` = "'.$name_id.'") 
            AND (`at_name`.`store_id` = '.$store.')) AS `product_name_table`
        ON (`main_table`.`product_id` = `product_name_table`.`entity_id`)
LEFT JOIN (SELECT `e`.`entity_id`, `at_price`.`value` AS `price`  
        FROM `catalog_product_entity` AS `e` 
        INNER JOIN `catalog_product_entity_decimal` AS `at_price` 
                ON (`at_price`.`entity_id` = `e`.`entity_id`) 
                AND (`at_price`.`attribute_id` = "'.$price_id.'") 
                AND (`at_price`.`store_id` = '.$store.')) AS `product_price_table`
        ON (`main_table`.`product_id` = `product_price_table`.`entity_id`)

GROUP BY `main_table`.`answer_id`, `main_table`.`product_id` 
ORDER BY `answer_id` ASC'

如何在" join"中进行嵌套选择? ?任何建议和帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

Zend_Db_Select有一个__toString()方法,所以我很确定你可以为连接构造嵌套选择,然后在主查询中使用它。像这样......

// $adapter is your Zend_Db_Adapter...
$joinConditionName = '`at_name`.`entity_id` = `e`.`entity_id`' 
    . $adapter->quoteInto('`at_name`.`attribute_id` = ?', $name_id)
    . $adapter->quoteInfo('`at_name`.`store_id` = ?', $store);
$subQueryName = new Zend_Db_Select();
$subQueryName->from(array('e' => 'catalog_product_entity'))
    ->join(
         'at_name' => 'catalog_product_entity', 
         $joinConditionName
    )->columns(array('e.entity_id', 'at_name.value'));


// and then the main query
$query = new Zend_Db_Select();
$query->from('main_table' => 'nanorepwidgets_answer')
    ->joinLeft(array('product_name_table' => $subQueryName->__toString()),
        'main_table.product_id = produce_name_table.entity_id')

或者我认为,这些方面应该有所作为。它没有记录,但是读取源(1.12)你可以传递一个Zend_Db_Select作为joinLeft的第一个参数,然后你的子查询将需要定义别名。我想,所有这些都是相同的。

您还可以通过使用更简单的ON子句(at_name.entity_id = e.entity_id)然后使用 - > where('at_name.attribute_id =?',$ name_id)在子选择中更容易引用。这样就不需要$ joinConditionName位了。

我很确定我已经做到了这一点,虽然我现在找不到,所以如果细节不太正确就道歉。