2012-11-13 104 views
0

我有在查詢構建定製「列」一個半複雜的select語句,結果需要由本專欄的結果進行過濾。有什麼方法可以在謂詞中引用此列?你會看到我想在where子句中註釋掉,在'On Sale'上過濾。是否可以在where子句中使用named select?

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

你可以做你濾波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

+0

謝謝!我最初嘗試過,但是不小心使用了引號而不是列名的反引號。咄.... – Jamey

相關問題