我正在编写一个查询来使用全文搜索来搜索 mysql 表:
select title,
MATCH(title,sidebarTxt,introTxt,fullTxt) AGAINST ('MY KEYWORDS' IN NATURAL LANGUAGE MODE) AS score
from tbl_news
where (status='published')
order by score DESC
上面的查询运行良好。但是,如果我尝试在 where 子句中使用 'score',MySql 会抛出错误“#1054 - 'where 子句'中的未知列 'score'。以下是不起作用的代码:
select title,
MATCH(title,sidebarTxt,introTxt,fullTxt) AGAINST ('MY KEYWORDS' IN NATURAL LANGUAGE MODE) AS score
from tbl_news
where status='published' and score > 0
order by score DESC
如果您能帮助我理解它,我将非常感激。
最佳答案
如果 score
是计算列,则不能在 WHERE
子句中使用 score
。您必须在附加的 HAVING
子句中设置它,才能在计算之后应用条件:
SELECT title,
MATCH(title,sidebarTxt,introTxt,fullTxt)
AGAINST ('MY KEYWORDS' IN NATURAL LANGUAGE MODE) AS score
FROM tbl_news
WHERE status='published'
HAVING score > 0
ORDER BY score DESC;
一个测试用例(使用不同的表)。这里 host
是一个列,host2
是一个派生列。当然,列推导和选择是伪造的并且没有什么意义:
mysql> use mysql;
Database changed
mysql> select host, UPPER(host) as host2 FROM user WHERE host = 'nottingham';
+------------+------------+
| host | host2 |
+------------+------------+
| nottingham | NOTTINGHAM |
+------------+------------+
1 row in set (0.00 sec)
mysql> select host, UPPER(host) as host2 FROM user WHERE host = 'nottingham' AND host2 = 'NOTTINGHAM';
ERROR 1054 (42S22): Unknown column 'host2' in 'where clause'
mysql> select host, UPPER(host) as 'host2' FROM user WHERE host = 'nottingham' AND host2 = 'NOTTINGHAM';
ERROR 1054 (42S22): Unknown column 'host2' in 'where clause'
mysql> select host, UPPER(host) as `host2` FROM user WHERE host = 'nottingham' AND host2 = 'NOTTINGHAM';
ERROR 1054 (42S22): Unknown column 'host2' in 'where clause'
mysql> select host, UPPER(host) as host2 FROM user WHERE host = 'nottingham' HAVING host2 = 'NOTTINGHAM';
+------------+------------+
| host | host2 |
+------------+------------+
| nottingham | NOTTINGHAM |
+------------+------------+
1 row in set (0.00 sec)
关于php - 全文Sql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12409145/