|
dbfiddle
. u# v& u) }( V% z3 Y8 i8 y% }CREATE TABLE logistics id int primary key, campaign VARCHAR inbound_date VARCHAR outbound_date VARCHAR(255));INSERT INTO logistics(id,campaign,inbound_date,outbound_date)VALUES ("1","C001","2019-01-01","2019-02-08"),("2","C001","2019-05-10","2019-05-12"),("3","C001","2019-06-12","2019-06-15"),("4","C001","2019-08-13","2019-08-20"),("5","C001","2019-11-14","2019-11-22");在上表中,我有一个列inbound_date和outbound_date日期值。
9 G& G6 { K1 h; V. t在我的查询中,coalesce他们把它命名为event_date。
8 B1 g& V& }9 L5 a: G) t% ~3 j! j现在,我想coalesce在WHERE别名用于查询的子句,但有错误Unknown column 'event_date' in 'whereclause':. t9 _: L1 J |8 L- t
SELECTcampaign,coalesce(inbound_date,outbound_date) as event_dateFROM logisticsWHEREevent_date BETWEEN "2019-06-01" AND "2019-10-01"我知道我可以在句子中使用它inbound_date和outbound_date解决这个问题是两个单独的条件,WHERE但是没有聪明的方法可以使用别名coalesce吗?
2 {! o5 X& U+ W+ |0 d& a 8 k5 p% U! F5 V6 ?- {
解决方案: 8 y2 ?0 J2 P: i
您可以重复表单或使用表单having子句:
: [- Z1 k3 h; I0 V; ^+ P4 ^SELECT campaign, coalesce(inbound_date,outbound_date) as event_dateFROM logisticsHAVING event_date BETWEEN '2019-06-01' AND '2019-10-01';我不建议在MySQL中用子查询。MySQL有实现子查询的趋势(尽管随着最新版本的改进)。这可能会阻碍优化。 |
|