dbfiddle
CREATE TABLE logistics ( id int primary key, campaign VARCHAR(255), inbound_date VARCHAR(255), 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日期值。 在我的查询中,coalesce他们将其命名为event_date。
inbound_date
outbound_date
coalesce
event_date
现在,我想coalesce在WHERE查询的子句中使用别名,但出现错误Unknown column 'event_date' in 'where clause':
WHERE
Unknown column 'event_date' in 'where clause'
SELECT campaign, coalesce(inbound_date, outbound_date) as event_date FROM logistics WHERE event_date BETWEEN "2019-06-01" AND "2019-10-01"
我知道我可以通过在子句中使用inbound_date和outbound_date作为两个单独的条件来解决此问题,WHERE但是使用别名没有聪明的方法coalesce吗?
您可以重复该表达式或使用一个having子句:
having
SELECT campaign, coalesce(inbound_date, outbound_date) as event_date FROM logistics HAVING event_date BETWEEN '2019-06-01' AND '2019-10-01';
我不建议在MySQL中使用子查询。MySQL具有实现子查询的趋势(尽管随着最新版本的改进)。这可能会阻碍优化。