我有一个可以简化为的SQL:
SELECT *
FROM table
WHERE LOCATE( column, :keyword ) > 0
ORDER BY LOCATE( column, :keyword )
您可以看到“LOCATE(column,:keyword)”的副本。有没有办法只计算一次?
答案 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