0

我有一个半复杂的选择语句,它在查询中构建了一个自定义“列”,结果需要通过该列的结果进行过滤。有什么方法可以在谓词中引用此列吗?您会在 where 子句中看到我想做的事情被注释掉了,过滤了“On Sale”。

select
p.prod_id,
case
  when p.subtitle is null then p.title
  else concat(p.title, ': ', p.subtitle)
end as 'Title',
p.issue as 'Issue',
e.abbrv as 'Editor',
p.jobnum as 'Job Number',
p.price as 'Price',
ship.due_date as 'Ship Date',
case
  when pi.onsale_minus_ship_date is not null then ship.due_date + interval pi.onsale_minus_ship_date day
  else
    case
      when prs.days_for_shipping != 0 then ship.due_date + interval prs.days_for_shipping day
      else ship.due_date + interval 7 day
    end
end as 'On Sale',
sale.due_date as 'Bookstore On Sale'
from products p

join schedules ship on ship.prod_id = p.prod_id and ship.milestone = 49
left join schedules sale on sale.prod_id = p.prod_id and sale.milestone = 647
left join editors e on find_in_set(e.id, p.editor)
left join printing_info pi on pi.prod_id = p.prod_id
left join printers prs on prs.id = pi.printer

where p.prod_type in (2, 3, 5, 6) -- physical, non comics (trades, hc, etc.)
--and 'On Sale' >= '$start_date' + interval 2 month
--and 'On Sale' <= '$end_date' + interval 2 month

order by ship.due_date asc, p.title asc
4

1 回答 1

1

您可以在HAVING子句中进行过滤 - 不幸的是,您不能在WHERE子句中引用列别名。

HAVING `On Sale` >= '$start_date' + interval 2 month
AND `On Sale` <= '$end_date' + interval 2 month

http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html

于 2012-11-13T20:19:13.477 回答