非常に単純な質問 (いくつかの場合): select サブクエリの結果を where 句で使用することは可能ですか?
私は現在、次のようなものを使用しています:
SELECT companies.id
, companies.name
, (SELECT COUNT(*)
FROM orders
WHERE
orders.company_id = companies.id
AND
orders.scheduled_at BETWEEN '2012-08-01 00:00:00' AND '2012-10-31 23:59:59'
) AS number_of_rides
FROM companies
WHERE
(SELECT COUNT(*)
FROM orders
WHERE
orders.company_id = companies.id
AND
orders.scheduled_at BETWEEN '2012-08-01 00:00:00' AND '2012-10-31 23:59:59'
) != 0
AND
companies.affiliate = 0
AND
companies.id = 346
これにより、同じクエリが 2 回実行されます。1 回は select で、もう 1 回は where で実行されます。次のように見える場所で選択サブクエリを参照することはまったく可能ですか:
SELECT companies.id
, companies.name
, (SELECT COUNT(*) AS number_of_rides
FROM orders
WHERE
orders.company_id = companies.id
AND
orders.scheduled_at BETWEEN '2012-08-01 00:00:00' AND '2012-10-31 23:59:59'
) AS x
FROM companies
WHERE
x.number_of_rides != 0
AND
companies.affiliate = 0
これは現時点では機能しません。これも機能しません。
SELECT companies.id
, companies.name
, (SELECT COUNT(*)
FROM orders
WHERE
orders.company_id = companies.id
AND
orders.scheduled_at BETWEEN '2012-08-01 00:00:00' AND '2012-10-31 23:59:59'
) AS number_of_rides
FROM companies
WHERE
number_of_rides != 0
AND
companies.affiliate = 0
クエリで2回実行しなくても可能ですか?
編集:わかりました。場合によっては GROUP BY を使用できないこともありますが、この場合は達成する必要がありました。それが私がしたことです:
SELECT companies.id
, companies.name
, (SELECT COUNT(*)
FROM orders
WHERE
orders.company_id = companies.id
AND
orders.scheduled_at BETWEEN '2012-08-01 00:00:00' AND '2012-10-31 23:59:59'
) AS number_of_rides
FROM companies
WHERE
companies.affiliate = 0
GROUP BY companies.id
HAVING number_of_rides != 0
なぜWHEREがSELECTのサブクエリ結果にアクセスできず、HAVINGがアクセスできないのかについての技術的な説明があるかどうか知りたいです...