如何消除SQL中的重复计算?

时间:2009-10-20 15:55:11

标签: sql mysql query-optimization

我有一个可以简化为的SQL:

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

您可以看到“LOCATE(column,:keyword)”的副本。有没有办法只计算一次?

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:2)

杰夫奥伯有正确的想法,但这是另一种方法:

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

答案 2 :(得分:2)

HAVING在MySQL中使用别名:

SELECT *, LOCATE( column, :keyword ) AS somelabel 
FROM table 
HAVING somelabel > 0 
ORDER BY somelabel