0

有人可以解释一下吗。我的 SQL:

SELECT 
    `offers`.`id`, 
    `offers`.`max_available`, 
    (SELECT COUNT( coupons.id ) FROM coupons WHERE coupons.status = 'Y' AND coupons.offer_id = offers.id) AS coupons_sold
FROM 
    `offers`
WHERE 
    `offers`.`status` IN ('P', 'S') AND 
    `offers`.`published_at` < 1341612000 AND 
    `offers`.`end_at` >1341567914 AND 
    `coupons_sold` < `offers`.`max_available` 
ORDER BY `offers`.`created_at` DESC
LIMIT 4 OFFSET 0 

这将返回我这 4 行:

id      max_available   coupons_sold
195     19              20
194     9999            0
193     9999            0
159     9999            93

ID 195如果我在 where 有这种情况,怎么可能包含该行coupons_sold < offers.max_available?我一无所知!

4

1 回答 1

3

此查询会产生错误,因为您不能使用列表中WHERE的别名 in 子句SELECT。除非表offers也有coupons_sold列!

试试这个查询,而不是:

SELECT id, max_available, coupons_sold
FROM
  ( SELECT 
        `offers`.`id`, 
        `offers`.`max_available`, 
        ( SELECT COUNT( coupons.id ) 
          FROM coupons 
          WHERE coupons.status = 'Y' 
            AND coupons.offer_id = offers.id
         ) AS coupons_sold
         offers.created_at
    FROM 
        `offers`
    WHERE 
        `offers`.`status` IN ('P', 'S') AND 
        `offers`.`published_at` < 1341612000 AND 
        `offers`.`end_at` >1341567914
  ) AS tmp
WHERE coupons_sold < max_available 
ORDER BY created_at DESC
  LIMIT 4 OFFSET 0 ;
于 2012-07-06T10:23:41.670 回答