Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to eliminate duplicate calculation in SQL?

I have a SQL that can be simplified to:

SELECT * 
  FROM table 
 WHERE LOCATE( column, :keyword ) > 0 
ORDER BY LOCATE( column, :keyword )

You can see there is a duplicate of "LOCATE( column, :keyword )". Is there a way to calculate it only once ?

like image 493
Cheng Avatar asked Jan 24 '23 02:01

Cheng


2 Answers

SELECT *, LOCATE( column, :keyword ) AS somelabel 
FROM table 
WHERE somelabel > 0 
ORDER BY somelabel
like image 130
Jeff Ober Avatar answered Jan 25 '23 14:01

Jeff Ober


HAVING works with aliases in MySQL:

SELECT *, LOCATE( column, :keyword ) AS somelabel 
FROM table 
HAVING somelabel > 0 
ORDER BY somelabel
like image 40
six8 Avatar answered Jan 25 '23 14:01

six8