我试图编写以下查询:
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);
但是,我想使用moreThan谓词:
$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)
答案 0 :(得分:2)
在您的情况下,确实没有必要使用子查询。您只需join
个表格。
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)
希望有所帮助