Very simple question (for some): is it possible to use select subquery result in where clause?
I’m currently using something like this:
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
This makes the same query run twice, once in select and the other in where. Is it possible at all to reference the select subquery in where to look something like this:
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
This doesn’t work at the moment, neither does this:
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
Is it possible at all without running it twice in the query?
Edit: OK. Although using GROUP BY wouldn’t be possible in some cases, it did what I needed to achieve in this case. That’s what I did:
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
I would still like to know if there’s a technical explanation as to why WHERE can’t access the subquery result in SELECT and HAVING can…
Try this