How to eliminate duplicate calculation in SQL?

时间秒杀一切 提交于 2019-12-10 16:37:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!