一尘不染

使用Zend DB编写子查询

mysql

我在将下面的SQL转换为Zend Db查询时遇到了一些问题。

$select = ' SELECT s.id, i.id as instance_id, i.reference, i.name, i.sic_code, i.start_date
                FROM sles s
                JOIN sle_instances i
                ON s.id = i.sle_id
                WHERE i.id = (  SELECT MAX(id) 
                                FROM sle_instances 
                                WHERE sle_id = s.id
                                )
                ORDER BY i.name ASC';

我之前已经了解了代码-但Zend Db无法正确生成查询。谁能告诉我我想念的东西吗?

$select = $db->select() ->from('sles', array(   'id',
                                                'instance_id'   => 'sle_instances.id',                                                                                          
                                                'reference'     => 'sle_instances.reference',           
                                                'name'          => 'sle_instances.name',
                                                'sic_code'      => 'sle_instances.sic_code',
                                                'start_date'    => 'sle_instances.start_date'
                                             )
                              )
                        ->join('sle_instances', 'sles.id = sle_instances.sle_id')
                        ->where('sles.id = (SELECT MAX(id) FROM sle_instances WHERE sle_id = sles.id)')
                        ->order('sle_instances.name ASC');

SQL确实可以正常工作。我想使用Zend Paginator功能来使用Zend Db重写它。

任何帮助是极大的赞赏。

J


阅读 233

收藏
2020-05-17

共1个答案

一尘不染

这个:

    $select = $db->select()->from(array("s" => "sles"), array("s.id","i.id as instanceid","i.reference","i.name","i.sic_code","i.start_date"))
                                 ->join(array('i' => "sle_instances"),"s.id = i.sle_id",array())
                                 ->where("i.id = (select max(id) from sle_instances where sle_id = s.id)")
                                 ->order('i.name asc');

给出以下内容:

"SELECT `s`.`id`, `i`.`id` AS `instanceid`, `i`.`reference`, `i`.`name`, `i`.`sic_code`, `i`.`start_date` FROM `sles` AS `s`
 INNER JOIN `sle_instances` AS `i` ON s.id = i.sle_id WHERE (i.id = (select max(id) from sle_instances where sle_id = s.id)) ORDER BY `i`.`name` asc"
2020-05-17