select中的SELECT结果无法达到?

时间:2019-07-02 10:35:01

标签: mysql sql

我在MySQL数据库中有以下查询:

SELECT o.*,
  (select IFNULL(sum(units_purchased),0) from member_purchase mp where 
    mp.offer_id = o.id and mp.is_deleted = 0) as sold_units
  FROM offer o 
  where o.partner_uid in ('941e08b6-f801-4656-8906-0a309b88c429') 
  and o.order_from < '2019-07-01' and o.order_to > '2019-07-10' and sold_units < o.servings and o.is_deleted = 0;

如果我删除

  

sold_units

... t运行正常,但是当我将其保留在其中时说:

  

where子句中的未知列“ sold_units”

有人知道这是什么原因吗?

3 个答案:

答案 0 :(得分:2)

不能在WHERE子句中引用列别名。这就是 SQL 语言的定义,并且在所有数据库中都是如此。

典型的解决方案是使用子查询,CTE或横向联接。

MySQL还有另一个解决方法。它允许在非聚合查询中使用HAVING子句。因此,您可以使用:

select o.*,
       (select coalesce(sum(units_purchased), 0) 
        from member_purchase mp
        where mp.offer_id = o.id and
              mp.is_deleted = 0
       ) as sold_units
from offer o
where o.partner_uid in ('941e08b6-f801-4656-8906-0a309b88c429') and
      o.order_from < '2019-07-01' and 
      o.order_to > '2019-07-10' and
      o.is_deleted = 0
having sold_units < o.servings;

答案 1 :(得分:1)

使用子查询

select * from 
(
  SELECT o.*,
  (select IFNULL(sum(units_purchased),0) from member_purchase mp where 
    mp.offer_id = o.id and mp.is_deleted = 0) as sold_units
  FROM offer o 
  where o.partner_uid in ('941e08b6-f801-4656-8906-0a309b88c429') 
  and o.order_from < '2019-07-01' and o.order_to > '2019-07-10'
)A where sold_units < servings and is_deleted = 0;

答案 2 :(得分:0)

好吧,根据@Raymond的建议,我最终得到了这个结果:

SELECT * FROM (SELECT o.*,
(select IFNULL(sum(units_purchased),0) from member_purchase mp where mp.offer_id = o.id and mp.is_deleted = 0) as sold_units
FROM offer o where o.partner_uid in ('941e08b6-f801-4656-8906-0a309b88c429') and o.order_from < '2019-07-02 10:00:00' and o.order_to > '2019-07-02 10:00:00' and o.is_deleted = 0) as results where results.sold_units < results.servings;