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.りんご
| 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です。see_name 'johnny' を含む 1 行だけではなく、apple id = 1 AND seed_name 'johnny' がこれらの結果のどこかにあるすべての行が必要です。Zend_Db_Select 経由で必要なものを取得できますか、それとも生の query() ルートに進む必要がありますか?
編集:質問を少し修正して、私が望むものに近づけ、少し明確にしようとしました。