mysql - 使用表达式查询选择大于

标签 mysql zend-framework zend-framework2

我正在尝试编写以下查询:

SELECT * FROM program
    WHERE (SELECT MAX(surface) FROM lot 
           WHERE lot.id_program=program.id) > $min_surface;       

以下代码有效:

$min_surface=40;
$select->where('(SELECT MAX(surface) FROM lot WHERE lot.id_program=program.id) > '.$min_surface);

但是,我想使用 GreaterThan 谓词:

$select->where->greaterThan(
     '(SELECT MAX(surface) FROM lot WHERE lot.id_program=program.id)'
     ,$min_surface
);

抛出以下错误:

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 
'`SELECT` `MAX``(``surface``)` `FROM` `lot` `WHERE` `lot`.`id_program``=``program' at line 1)

最佳答案

在您的情况下确实不需要使用子查询。您只需加入表即可。

SELECT program.*, MAX(surface) as max_surface 
FROM program
JOIN lot ON lot.id_program = program.id
GROUP BY program.id
HAVING max_surface > $min_surface

这个查询可以写

$select->from('program')
    ->join(
        'lot', 
        'lot.id_program = program.id', 
        array('max_surface' => new Zend_Db_Expr('MAX(surface)'))
    )
    ->group('program.id')
    ->having('max_surface > ?', $min_surface)

希望对你有帮助

关于mysql - 使用表达式查询选择大于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26481458/

相关文章:

html - 如何从内容中单独打印组显示?

php - ZF2 弃用 : ServiceManagerAwareInterface

php - 如何加入 laravel infyom 生成器?

PHP Mysql - 将数据库 ID 中的所有值加 1,下一个值减去 1

mysql - 在 loopback.io 中进行连接查询

php - PHP 应用程序中的 MySQL 字符编码 (öä)

zend-framework - 在前端 Controller 插件 Zend 中重定向

zend-framework2 - Zend Framework 多语言集成步骤

php - 具有 varchar id 的 Doctrine2 实体不将 id 插入数据库

mysql - 如何执行 SQL 查询跳过错误?