SQL调试 - 忽略条件

时间:2012-07-06 10:02:24

标签: mysql sql

有人可以解释一下这个。我的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中有这种情况,那么包含coupons_sold < offers.max_available的行怎么可能?我无能为力!

1 个答案:

答案 0 :(得分:3)

此查询会产生错误,因为您无法在WHERE子句中使用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 ;