我正在尝试使用 Zend_Db api 编写以下查询:
select * from tableA where id not in (select pid from tableB where x =46 and y='participated');
我编写了以下代码以使其正常工作:
首先,我从 tableB 中获取数组格式的 pid 列表:
$select = $this->select()
->from(array('tb' =>'tableB'), array('mylist' => new Zend_Db_Expr('group_concat(tb.pid)' )))
->where('x = ?', $xval) //$xval is coming as 46
->where('type = ?', 'participated');
$result = $this->getAdapter()->fetchAll($select);
error_log("Result of query1 is " . print_r($result, true));
//Convert to array
$mylistArr = preg_split('/,/' , $result[0]['mylist'], PREG_SPLIT_NO_EMPTY);
error_log("value of mylistArr is " . print_r($mylistArr, true));
//Now get the results from tableA
$selectta = $this->select()
->setIntegrityCheck(false)
->from(array('ta' => 'tableA'), array('ta.id', 'ta.first_name', 'ta.last_name'))
->where('ta.id not in (?)', $mylistArr[0]);
$result = $this->fetchAll($selectta);
error_log("db query result is " . print_r($result, true));
现在,问题是这样的:形成的最终查询是
SELECT `ta`.`id`, `ta`.`first_name`, `ta`.`last_name` FROM `tableA` AS `ta` WHERE (ta.id not in ('197,198,199,200,106,201,202,204,203,205'))
但是,我希望查询如下所示(也就是说,tableB 中的 id 列表不应包含在引号中):
SELECT `ta`.`id`, `ta`.`first_name`, `ta`.`last_name` FROM `tableA` AS `ta` WHERE (ta.id not in (197,198,199,200,106,201,202,204,203,205))
原因是,当在 IN 子句中传递逗号时,只会选取第一个 id 即 197 来过滤结果。
非常感谢任何帮助。
谢谢