How to use union in zend db

后端 未结 3 1006
小蘑菇
小蘑菇 2021-01-13 07:10

In sql i am using union i don\'t know how to write it in zend db.

select m.*, 0 as is_shared from test m where user_id = $userId 
union
select m.*,1 as is_sh         


        
相关标签:
3条回答
  • 2021-01-13 07:21

    According to the Zend_Db_Select documentation, you can create one query for each member of the union (they can be strings or Zend_Db_Select objects themselves), and then call the union() method of Zend_Db_Select.

    Something like:

    $sql1 = FIRSTPARTOFTHEQUERY;
    $sql2 = SECONDPARTOFTHEQUERY;
    $select = $db->select();
    $select->union(array($sql1, $sql2));
    

    Hope that helps,

    0 讨论(0)
  • 2021-01-13 07:40

    I don't know our sql is work. But it can make following code.

    $userId = 10;
    $email = 'bbsdf@sdf.sd';
    
    $select1 = $db->select()
                    ->from(array('m' => 'test'), array('*', '0 AS is_shared'))
                    ->where('user_id =?', $userId);
    
    $select2 = $db->select()
                    ->from(array('m' => 'test'), array('*', '1 AS is_shared'))
                    ->join(array('ms' => 'test_shares'), 'm.test_id = ms.test_id', '')
                    ->where('ms.email_address =?', $email)
                    ->where('m.url IS NULL');                  
    
    $select = $this->select()
         ->union(array($select1, $select2))
         ->order('title');
    
    echo $select; die;
    
            /*SELECT `m`.*, `m`.`0` AS `is_shared` 
             * FROM `test` AS `m` 
             * WHERE (user_id =10) 
             * UNION 
             * SELECT `m`.*, `m`.`1` AS `is_shared` 
             * FROM `test` AS `m` 
             * INNER JOIN `test_shares` AS `ms` 
             * ON m.test_id = ms.test_id 
             * WHERE (ms.email_address ='bbsdf@sdf.sd') AND (m.url IS NULL) 
             * ORDER BY `title` ASC*/
    
    0 讨论(0)
  • 2021-01-13 07:40

    For future reference, in Zend Framework 2.3 this is done with combine.

    For example:

        use \Zend\Db\Sql\Select;
        use \Zend\Db\Sql\Sql;
    
        $sql = new Sql(/* ADAPTER HERE */);
    
        $tag1 = new Select( ['a' => 'articles'] );
        $tag1->columns( [ 'tag' => 'first_tag'] );
        $tag1->where->in('a.id', $articleIds);
    
        $tag2 = new Select( ['a' => 'articles'] );
        $tag2->columns( [ 'tag' => 'second_tag'] );
        $tag2->where->in('a.id', $articleIds);
        $tag2->combine($tag1);
    
        $tag3 = new Select( ['a' => 'articles'] );
        $tag3->columns( [ 'tag' => 'third_tag'] );
        $tag3->where->in('a.id', $articleIds);
        $tag3->combine($tag2);
    
        $statement = $sql->prepareStatementForSqlObject($tag3);
    
    0 讨论(0)
提交回复
热议问题