Zend选择对象 - 构建查询

时间:2014-02-03 12:26:47

标签: sql zend-framework select inner-join

如何在Zend Select对象表示法中编写以下查询,以便使用 - > join() - > where()等?

    SELECT t.id, t.user_id, t.added_date, u.id, u.phone, bk.call_status 
FROM `transaction` t
INNER JOIN
    (
    SELECT id, MAX(added_date) AS addedDate
    FROM `transaction`
    GROUP BY id
    ) gt 
ON t.id = gt.id AND t.added_date = gt.addedDate
LEFT JOIN `user` u ON t.user_id = u.id
LEFT JOIN `bok_call` bk ON bk.user_id = t.user_id
WHERE NOT  t.user_id = 'null'
AND addedDate BETWEEN '2008-05-04 17:51:48' AND '2009-05-04 17:51:48'
AND NOT u.phone = ''
AND bk.call_status IS null

2 个答案:

答案 0 :(得分:2)

例如这样:

$joinSelect = $model->select()
                    ->from('transaction'), array('id', 'addedDate' => 'MAX(added_date)'))
                    ->group('id');

$select = $model->select()
                ->setIntegrityCheck(false)
                ->from(array('t' => 'transaction'), array('id', 'user_id', 'added_date'))
                ->join(array('gt' => $joinSelect), 't.id = gr.id AND t.added_date = gt.addedDate', array());
                ->joinLeft(array('u' => 'user'), 't.user_id = u.id', array('id', 'phone'))
                ->joinLeft(array('bk' => 'bok_call'), 'bk.user_id = t.user_id', array('call_status'))
                ->where('t.user_id != ?', 'null')
                ->where("addedDate BETWEEN '2008-05-04 17:51:48' AND '2009-05-04 17:51:48')
                ->where('u.phone != ?', '')
                ->where('bk.call_status IS NULL');

请注意,您无法区分结果中的't.id'和'u.id'。

答案 1 :(得分:0)

谢谢Mate! (DziękiDaniel;))我刚刚更正了一些括号和行

- > join(array('gt'=> $ joinSelect),'t.id = gt.id AND t.added_date = gt.addedDate',array());

这是gr.id

并删除了完整性检查,因为我没有使用数据库表只是Zend_Db_Adapter_Pdo_Mysql

它起作用了地狱:)。

有没有办法区分这两个名为ID的字段?它们都是数据库中的id并且没有机会更改它,因此唯一的方法是在结果中更改一次名称。

编辑:好的,得到它,只需将它们设置为在“trans_id”=>“id”,“trans_user_id”=>“user_id”,“trans_added_date”=>'等唯一键名称下返回ADDED_DATE'

有没有提供此类或更复杂示例示例的来源或图书?