是否可以在where子句中使用命名选择?

时间:2012-11-13 20:11:59

标签: mysql

我有一个半复杂的select语句,它在查询中构建自定义“列”,结果需要按此列的结果进行过滤。有没有办法在谓词中引用此列?你会在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

1 个答案:

答案 0 :(得分: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

相关问题