[英]How to use union in zend db
在我使用union的sql中我不知道如何在zend db中编写它。
select m.*, 0 as is_shared from test m where user_id = $userId
union
select m.*,1 as is_shared from test m
join test_shares ms
where m.test_id = ms.test_id
and ms.email_address = $email
and m.url is not null;
请帮帮我....
我试过这样但没用
$cols1 = array('test.*,0 as is_shared');
$select1 = $db->select ()
->from ( 'test', $cols1 )
->where ( 'user_id = ?', $userId);
$cols2 = array('test_shares.*', '1 as is_shared');
$select2 = $db->select ()
->from ( 'test', $cols2 )
->join ( 'test_shares', array () )
->where ( 'test.test_id = test_shares.test_id')
->where ( 'test_shares.email_address = ?', $email)
->where ( 'test.url is NOT NULL');
$select = $db->select()
->union(array($select1, $select2))
->order('title');
正在进行'测试'。'0'AS'is_shared'就像这样,但我需要这个0作为is_shared。 这是'测试'。'1'AS'is_shared'就像这样,但我需要这样的1 as isshared。
我不知道我们的sql是否正常工作。 但它可以制作以下代码。
$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*/
为了将来参考,在Zend Framework 2.3中,这是通过组合完成的。
例如:
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);
根据Zend_Db_Select文档 ,您可以为union的每个成员创建一个查询(它们可以是字符串或Zend_Db_Select
对象本身),然后调用Zend_Db_Select
的union()
方法。
就像是:
$sql1 = FIRSTPARTOFTHEQUERY;
$sql2 = SECONDPARTOFTHEQUERY;
$select = $db->select();
$select->union(array($sql1, $sql2));
希望有所帮助,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.