2

非常に単純な質問 (いくつかの場合): 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がアクセスできないのかについての技術的な説明があるかどうか知りたいです...

4

1 に答える 1

4

これを試して

Select 
    companies.id  , 
    companies.name,
    Tcount as number_of_rides
FROM companies
left join (
        select 
            id , 
            COUNT(*) as Tcount 
        FROM orders 
        where orders.scheduled_at BETWEEN '2012-08-01 00:00:00' AND '2012-10-31 23:59:59'
        ) as orders on orders.company_id = companies.id
WHERE companies.affiliate = 0 AND companies.id = 346
group by companies.id 
having number_of_rides != 0
于 2012-11-15T09:49:05.760 に答える