php - Zend_Db 子查询

标签 php zend-framework subquery zend-db zend-db-table

我一直在尝试使用 ZendFW 构建一个 sql 查询,但我似乎无法让它像我想要的那样运行(或根本无法运行)。这是我尝试使用 zend_db select() 构建的有效查询

SELECT tc.trip_title, td.ID, td.trip_id, 
  (SELECT count(*) FROM 'trips_invites' ti 
   WHERE ti.destination_id=td.ID AND ti.accepted ='NR') AS "pending_invites" 
FROM `trips_current` AS `tc`, `trips_data` AS `td` 
WHERE (tc.ID=td.trip_id) AND (tc.creator_id = '1') 
ORDER BY `trip_id` ASC 

我想不通的是如何正确地获取该子查询,而且我尝试的任何方法似乎都不起作用。

如有任何帮助,我们将不胜感激!

谢谢!

编辑/回答:如果有人遇到类似的问题,根据下面的建议,我按以下方式通过查询重新工作:

SELECT `tc`.`trip_title`, `td`.`ID`, `td`.`trip_id`, count(TI.ID)
FROM `trips_current` AS `tc` 
INNER JOIN `trips_data` AS `td` ON td.trip_id = tc.ID 
LEFT JOIN trips_invites AS TI ON ti.destination_id = td.id
WHERE tc.creator_id = 1  AND ti.accepted='NR'
GROUP BY td.id
ORDER BY `trip_id` ASC

我使用 ZendFW 以这种方式创建的:

$select = $this->dblink->select() 
->from(array('tc' => 'trips_current'),
      array('trip_title'))
->join(array('td' => 'trips_data'), 
'td.trip_id = tc.id',                   
      array('ID','trip_id'))
->joinLeft(array('ti'=>'trips_invites'),
     'ti.destination_id = td.id',
     array('COUNT(ti.id)'))
->where('tc.creator_id =?',1)
->group('td.id')
->order('trip_id');

最佳答案

您不需要子查询,您可以使用 GROUP BY 执行此操作:

$select = $db->select()
  ->from(array("tc"=>"trips_current"), array("trip_title"))
  ->join(array("td"=>"trips_data"), "td.trip_id = tc.ID", array("ID", "trip_id"))
  ->joinLeft(array("ti"=>"trips_invites"), "ti.destination_id = td.ID", array("COUNT(*)")
  ->where("tc.creator_id = ?", 1)
  ->group(array("tc.ID", "td.ID"))
  ->order("trip_id");

我假设您使用的是 MySQL。由于 MySQL 允许的非标准行为,分组方式更简单。

编辑: 我将上面的查询更改为对 ti 使用 joinLeft()。这是为了防止给定目的地没有邀请,正如您在评论中提到的那样。


如果你真的需要使用子查询,你可以单独创建它,然后将它插入到你的主查询的选择列表中:

$subquery = $db->select()
  ->from(array("ti"=>"trips_invites", "COUNT(*)")
  ->where("ti.destination_id = td.ID");

$select = $db->select()
  ->from(array("tc"=>"trips_current"), array("trip_title", "($subquery)"))
  ->join(array("td"=>"trips_data"), "td.trip_id = tc.ID", array("ID", "trip_id"))
  ->where("tc.creator_id = ?", 1)
  ->order("trip_id");

Zend_Db_Select 知道在您的选择列表中指定的列中查找括号并跳过分隔这些列。

我还想指出,您不必仅仅因为它在那里就必须使用 Zend_Db_Select。当您需要使用依赖于变量或应用程序逻辑的部分构建查询时,该类最适合。如果您知道完整的 SQL 查询并且它不依赖于应用程序条件,那么将它写成字符串会更清楚——就像您在原始问题中写的一样。

关于php - Zend_Db 子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3221285/

相关文章:

php - 数千个数字的正则表达式

php - 记录用户点击的内容

sql - ISNULL、IIF、CASE 语句中的子查询

php - 有没有办法让 FPDF/FPDI 或 Zend_Pdf 支持解析大于 1.4 的 PDF?

php - ZF : performing redirect inside model

php - Cakephp 3 中带有子查询的 mysql FROM 子句

mysql - 在 MySQL 行的 100 列中选择至少 6 个值

php - MYSQL SELECT WITH LEFT JOIN LIMIT 1

javascript - 刷新div而不用jquery重新加载页面

php - 在 PHP 中反序列化以恢复为对象