开发者

How to simplify a repeatable pattern in SQL query?

开发者 https://www.devze.com 2023-03-27 16:09 出处:网络
Is that possible to simplify: SELECT GREATEST(a,b) FROM my_table WHERE GREATEST(a,b) > 25 to something like:开发者_运维百科

Is that possible to simplify:

SELECT GREATEST(a,b)
FROM my_table 
WHERE GREATEST(a,b) > 25

to something like:

开发者_运维百科
SELECT GREATEST(a,b) AS max_a_b 
FROM my_table 
WHERE max_a_b > 25

This try returns:

Unknown column 'max_a_b' in 'where clause'


SELECT GREATEST(a,b) AS max_a_b 
FROM my_table 
HAVING max_a_b > 25

At where level your alias doesn't exist while it exists if you use having clause.


SELECT max_a_b
FROM (SELECT GREATEST(a,b) AS max_a_b 
      FROM my_table)
WHERE max_a_b > 25

This should work, but it's questionable if this simplifies the query. Repeating the GREATEST(a,b) in the WHERE clause is fine, imo.


MySQL doesn't run the GREATEST(a,b) twice, for what it's worth.


The statement is still simple. And when your question is about optimization then this is better done by DBMS rather than you.

0

精彩评论

暂无评论...
验证码 换一张
取 消