问题
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 ?
回答1:
HAVING works with aliases in MySQL:
SELECT *, LOCATE( column, :keyword ) AS somelabel
FROM table
HAVING somelabel > 0
ORDER BY somelabel
回答2:
SELECT *, LOCATE( column, :keyword ) AS somelabel
FROM table
WHERE somelabel > 0
ORDER BY somelabel
回答3:
Jeff Ober has the right idea, but here is an alternative method:
SELECT
t.*
,loc.LOCATED
FROM
table t
INNER JOIN
(
SELECT
primary_key
,LOCATE(column,:keyword) AS LOCATED
FROM
table
) loc
ON t.primary_key = loc.primary_key
WHERE loc.LOCATED > 0
ORDER BY
loc.LOCATED
来源:https://stackoverflow.com/questions/1595659/how-to-eliminate-duplicate-calculation-in-sql