php - 全文Sql查询

标签 php mysql

我正在编写一个查询来使用全文搜索来搜索 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/

相关文章:

PHP为任何数据库编写程序

php - 即使将 html 和 php 设置为 UTF-8,£ 仍然出现在电子邮件中

php - Zend 框架 2 错误 : Statement could not be executed when implement year function in table gateway

php - 刷新页面时,fsockopen 并不总是执行 mysql 查询

mysql - 复杂 MySQL 子查询的语法错误

php - 在php中强制下载

php - 合并 mysql 中的两个表以获得最近的事件功能

Mysql 用另一个表中的值更新 Null 列并重复该顺序

mysql - 横幅旋转器绑定(bind)到应用程序范围而不是数据库?

php - 更新 mysql 中的逗号分隔列表