如何在没有括号的Zend_Db_Select语句中使用“HAVING”子句?

时间:2011-10-28 06:42:13

标签: php mysql database zend-db having

我知道Zend提供了一个having()方法,但我想要的是一个类似的查询:

SELECT a.*, `as`.* FROM `fruit_db`.`apples` AS `a`
INNER JOIN `fruit_db`.`apple_seeds` AS `as` ON a.id = as.apple_id
WHERE (a.id = 1) AND as.seed_name HAVING 'johnny'

不是“HAVING(as.seed_name ='johnny')”

回溯一下,我们有表格:

fruit_db.apples

| id  | name |
--------------
|  1  | red  |
|  2  | green|

fruit_db.apple_seeds

| apple_id | seed_name | 
------------------------
| 1        | johnny    |
| 1        | judy      |
| 2        | granny    |

我想要的结果如下:

| id  | name | apple_id | seed_name |
-------------------------------------
| 1   | red  |    1     | johnny    |
| 1   | red  |    1     | judy      |

上面提供的查询给出了这个结果,但是使用Zend_Db_Select将括号括在having和where语句的每个部分周围,这些部分使我的查询无效。所以

$zend_db_table->select()
 ->setIntegrityCheck(false)
 ->from(array("a" => "apples"), array("*"))
 ->join(array("as"=>"apple_seeds"),
     "a.id = as.apple_id",
   array("*"))
 ->where('a.id = 1')
 ->where('as.seed_name HAVING "johnny"');

产生

SELECT a.*, `as`.* FROM `fruit_db`.`apples` AS `a`
INNER JOIN `fruit_db`.`apple_seeds` AS `as` ON a.id = as.apple_id
WHERE (a.id = 1) AND (as.seed_name HAVING 'johnny')

哪个是无效的SQL。简而言之:

SELECT a.*, `as`.* FROM `fruit_db`.`apples` AS `a`
INNER JOIN `fruit_db`.`apple_seeds` AS `as` ON a.id = as.apple_id
WHERE (a.id = 1) AND as.seed_name HAVING 'johnny'

有效,但是:

SELECT a.*, `as`.* FROM `fruit_db`.`apples` AS `a`
INNER JOIN `fruit_db`.`apple_seeds` AS `as` ON a.id = as.apple_id
WHERE (a.id = 1) AND (as.seed_name HAVING 'johnny')
Zend生成的

是无效的SQL。我不希望只有一行看到了'johnny',我想要所有行,其中apple id = 1 AND seed_name'johnny'就在这些结果的某个地方。我可以通过Zend_Db_Select得到我需要的东西,还是需要去原始查询()路线?

编辑:我已将问题修改为更接近我想要的内容并试图澄清一下。

1 个答案:

答案 0 :(得分:1)

变化

- > where('as.apple_id HAVING 1');

- >有('as.apple_id = 1');

http://framework.zend.com/manual/en/zend.db.select.html