简体   繁体   中英

How use UNION and Zend DB if number of columns different

I need get information from two different tables. Like:

table1 (col1, col2, col3, col4)

table2 (col1, col2)

I try use UNION for it. If type:

$res = $db->query('
SELECT col1, col2, col3, col4 FROM table1
UNION SELECT col1, col2, null, null FROM table2
')->fetchAll();

Code work correct, I had result.

But I need use Zend_DB_Adapter, so I try like

$select2 = $db->select()->from(['t2' => 'table2'], ['col1', 'col2', new Zend_Db_Expr("null"), new Zend_Db_Expr('null')]);
$select1 = $db->select()->from(['t1'=>'table1'], ['col1', 'col2', 'col3', 'col4']);
$select = $db->select()->union([$select1, $select2], Zend_Db_Select::SQL_UNION);
$res = $db->query($select)->fetchAll();

This attempt got only 3 columns and last had false for each rows.

If change it like:

$db->select()->from(['t2' => 'table2'], ['col1', 'col2', null, null]);

I had error: "each UNION query must have the same number of columns"

Please, help me use Zend_DB and UNION with number of columns different.

It's work

$select2 = $db->select()->from(['t2' => 'table2'], ['col1', 'col2', 'col3' => new Zend_Db_Expr("null"), 'col4' => new Zend_Db_Expr('null')]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM