zend-db中的UNION SELECT由于语法错误而失败

时间:2019-08-15 14:14:32

标签: php sql zend-framework

使用zend-db构造UNION SELECT时遇到问题。我想将三个SELECT结合在一起:

( SELECT `id1` AS `id` FROM `table1` ) UNION ( SELECT `id2` AS `id2` FROM `table2` ) UNION ( SELECT `id3` AS `id` FROM `table3` )

ID字段的计数,顺序和数据类型相等,并且执行查询时没有任何错误。
然后,我尝试通过zend-db构建此查询:

$select1 = new Select();
$select1->from('table1');
$select1->columns(['id1']);

$select2 = new Select();
$select2->from('table2');
$select2->columns(['id2']);

$select3 = new Select();
$select3->from('table3');
$select3->columns(['id3']);

$select2->combine($select1, Select::COMBINE_UNION);
$select3->combine($select2, Select::COMBINE_UNION);

这将导致以下查询(从日志中获取):

( SELECT `id1` AS `id` FROM `table1` ) UNION (( SELECT `id2` AS `id2` FROM `table2` ) UNION ( SELECT `id3` AS `id` FROM `table3` ))

由于第二个UNION错误,因此出现SQL语法错误。
确切的错误消息如下:

"exception": {
    "class": "Zend\\Db\\Adapter\\Exception\\InvalidQueryException",
    "code": 0,
    "message": "Statement could not be executed (42000 - 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION ( SELECT `id3` AS `id`' at line 1)"
}

我还尝试通过这种方式组合SELECT:

$select1->combine($select2, Select::COMBINE_UNION)->combine($select3, Select::COMBINE_UNION);

但随后出现以下异常:

"exception": {
    "class": "Zend\\Db\\Sql\\Exception\\InvalidArgumentException",
    "code": 0,
    "message": "This Select object is already combined and cannot be combined with multiple Selects objects"
}

1 个答案:

答案 0 :(得分:0)

实际的错误消息是什么?

不确定是否会产生任何效果,但尝试显式CAST转换“顶部”查询中返回的数据类型:

( 
  SELECT CAST(`id1` AS <data_type>) AS `id` FROM `table1` 
) 
UNION 
(
  ( SELECT CAST(`id2` AS <data_type>) AS `id2` FROM `table2` ) 
  UNION 
  ( SELECT `id3` AS `id` FROM `table3` )
)
相关问题