Search code examples
mysqlzend-frameworkzend-framework2zend-dbzend-framework3

Union of two tables in Zend 2


I want to union two tables with where clause in zf2:-

table1 app_followers
table2 app_users
where condition could be anything
and order by updated_date.

Please let me know the query for zend 2.

Thanks..


Solution

  • Using UNION is ZF2:

    Using ZF2 dedicated class Combine Zend\Db\Sql\Combine

        new Combine(
         [
          $select1,
          $select2,
          $select3,
           ...
         ]
        )
    

    A detailed example which uses combine is as follows:

    $select1 = $sql->select('java');
    $select2 = $sql->select('dotnet');
    $select1->combine($select2);
    
    $select3 = $sql->select('android');
    
    $selectall3 = $sql->select();
    $selectall3->from(array('sel1and2' => $select1));
    $selectall3->combine($select3);
    
    $select4 = $sql->select('network');
    
    $selectall4 = $sql->select();
    $selectall4->from(array('sel1and2and3' => $selectall3));
    $selectall4->combine($select4);
    
    $select5 = $sql->select('dmining');
    
    $selectall5 = $sql->select();
    $selectall5->from(array('sel1and2and3and4' => $selectall4));
    $selectall5->combine($select5);
    

    which is equivalent to the normal SQL query for UNION:

    SELECT * FROM java 
    UNION SELECT * from dotnet 
    UNION SELECT * from android 
    UNION SELECT * from network;
    UNION SELECT * from dmining;
    

    I hope it helps.