2

非常简单的问题(对于某些人):是否可以在 where 子句中使用 select 子查询结果?

我目前正在使用这样的东西:

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

这使得相同的查询运行两次,一次在 select 中,另一次在 where 中。是否有可能在 where 中引用 select 子查询,如下所示:

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

是否有可能在查询中不运行两次?

编辑:好的。尽管在某些情况下无法使用 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 回答