我正在this post。
中描述的mysql中实现一个简单的搜索我的代码与给出的示例非常相似:
SELECT
SUM(((LENGTH(p.body) - LENGTH(REPLACE(p.body, 'term', '')))/4) +
((LENGTH(p.body) - LENGTH(REPLACE(p.body, 'search', '')))/6))
AS Occurrences
FROM
posts AS p
GROUP BY
p.id
ORDER BY
Occurrences DESC
运作良好。问题是我只想选择出现次数大于0的行(即显示与搜索有关的行)。
我尝试过添加
WHERE Occurrences>0
制作整个代码块:
SELECT
SUM(((LENGTH(p.body) - LENGTH(REPLACE(p.body, 'term', '')))/4) +
((LENGTH(p.body) - LENGTH(REPLACE(p.body, 'search', '')))/6))
AS Occurrences
FROM
posts AS p
WHERE Occurrences>0
GROUP BY
p.id
ORDER BY
Occurrences DESC
但这总是会导致查询错误。我已经尝试了其他WHERE子句进行测试,我发现在尝试使用Occurrences变量时我只会遇到错误。
错误是,正如您所料:
Unknown column 'Occurrences' in 'where clause'
有没有办法做我想做的事情?我宁愿不必选择所有行,然后在php中裁掉我不想要的那些,这看起来非常低效。
答案 0 :(得分:0)
试试这个:
SELECT Occurrences FROM (
SELECT
SUM(((LENGTH(p.body) - LENGTH(REPLACE(p.body, 'term', '')))/4) +
((LENGTH(p.body) - LENGTH(REPLACE(p.body, 'search', '')))/6))
AS Occurrences
FROM
posts AS p
GROUP BY
p.id
) AS IQ
WHERE Occurrences > 0
ORDER BY
Occurrences DESC
答案 1 :(得分:0)
您不能在WHERE
子句中使用别名,仅在ODER BY
和HAVING
中的某些SQL方言中使用别名,因此您可以尝试使用HAVING
< / p>
SELECT
SUM(((LENGTH(p.body) - LENGTH(REPLACE(p.body, 'term', '')))/4) +
((LENGTH(p.body) - LENGTH(REPLACE(p.body, 'search', '')))/6))
AS Occurrences
FROM
posts AS p
GROUP BY
p.id
HAVING Occurrences>0
ORDER BY
Occurrences DESC
有些问题引用in the mysql docs