如何提取 SQL 查询中的重复表达式?列别名似乎不是问题
所以,我有一个看起来像这样的查询:
SELECT id,
DATE_FORMAT(CONVERT_TZ(callTime,'+0:00','-7:00'),'%b %d %Y') as callDate,
DATE_FORMAT(CONVERT_TZ(callTime,'+0:00','-7:00'),'%H:%i') as callTimeOfDay,
SEC_TO_TIME(callLength) as callLength
FROM cs_calldata WHERE
customerCode='999999-abc-blahblahblah' AND
CONVERT_TZ(callTime,'+0:00','-7:00') >= '2010-04-25' AND
CONVERT_TZ(callTime,'+0:00','-7:00') <= '2010-05-25'
如果你像我一样,你可能会开始思考,如果我不要求它计算,也许它会提高可读性,甚至可能提高该查询的性能CONVERT_TZ(callTime,'+0:00','-7:00')
四个单独的时间。
因此,我尝试为该表达式创建一个列别名,并用该别名替换以后出现的情况:
SELECT id,
CONVERT_TZ(callTime,'+0:00','-7:00') as callTimeZoned,
DATE_FORMAT(callTimeZoned,'%b %d %Y') as callDate,
DATE_FORMAT(callTimeZoned,'%H:%i') as callTimeOfDay,
SEC_TO_TIME(callLength) as callLength
FROM cs_calldata WHERE
customerCode='5999999-abc-blahblahblah' AND
callTimeZoned >= '2010-04-25' AND
callTimeZoned <= '2010-05-25'
这是我了解到的,引用 MySQL 手册:
标准 SQL 不允许引用 WHERE 子句中的列别名。这 施加限制是因为当 WHERE 子句被求值时, 列值可能尚未确定 确定。
因此,这种方法似乎已经行不通了。
用这样的重复表达式编写查询的人应该如何处理它?
So, I've got a query that looks something like this:
SELECT id,
DATE_FORMAT(CONVERT_TZ(callTime,'+0:00','-7:00'),'%b %d %Y') as callDate,
DATE_FORMAT(CONVERT_TZ(callTime,'+0:00','-7:00'),'%H:%i') as callTimeOfDay,
SEC_TO_TIME(callLength) as callLength
FROM cs_calldata WHERE
customerCode='999999-abc-blahblahblah' AND
CONVERT_TZ(callTime,'+0:00','-7:00') >= '2010-04-25' AND
CONVERT_TZ(callTime,'+0:00','-7:00') <= '2010-05-25'
If you're like me, you probably start thinking that maybe it would improve readability and possibly the performance of this query if I wasn't asking it to compute CONVERT_TZ(callTime,'+0:00','-7:00')
four separate times.
So I try to create a column alias for that expression and replace further occurances with that alias:
SELECT id,
CONVERT_TZ(callTime,'+0:00','-7:00') as callTimeZoned,
DATE_FORMAT(callTimeZoned,'%b %d %Y') as callDate,
DATE_FORMAT(callTimeZoned,'%H:%i') as callTimeOfDay,
SEC_TO_TIME(callLength) as callLength
FROM cs_calldata WHERE
customerCode='5999999-abc-blahblahblah' AND
callTimeZoned >= '2010-04-25' AND
callTimeZoned <= '2010-05-25'
This is when I learned, to quote the MySQL manual:
Standard SQL disallows references to
column aliases in a WHERE clause. This
restriction is imposed because when
the WHERE clause is evaluated, the
column value may not yet have been
determined.
So, that approach would seem to be dead in the water.
How is someone writing queries with recurring expressions like this supposed to deal with it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在派生表中定义别名,然后在外部查询中引用它们:
You can define aliases in a derived table and then reference them in the outer query:
(请注意倒数第三行从
AND
到having
的切换。)(Note the switch from
AND
tohaving
on the third to last line.)