0

如本文所述,我正在 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 中裁剪出我不想要的行,这似乎非常低效。

4

2 回答 2

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
于 2013-07-20T17:38:43.873 回答
0

您不能在WHERE子句中使用别名,只能在ODER BY和一些 SQL 方言中使用别名HAVING,因此您可以尝试使用HAVING

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

mysql docs中对问题的一些参考

于 2013-07-20T17:42:12.937 回答