Mysql SQL返回每行满足的条件数

Mysql SQL返回每行满足的条件数,mysql,sql,Mysql,Sql,我试图通过在每行中应用的满足条件的数量来排序结果集 如果我有下表 ++++++++++++++++++++++++++++++++++++++ book_id | book_title ++++++++++++++++++++++++++++++++++++++ | 54 | Learn SQL the easy way | 56 | Mastering PHP | 58 | PHP, MySQL Bible | 59 | The complete guide to SQ

我试图通过在每行中应用的满足条件的数量来排序结果集

如果我有下表

++++++++++++++++++++++++++++++++++++++
book_id | book_title
++++++++++++++++++++++++++++++++++++++
|  54   | Learn SQL the easy way
|  56   | Mastering PHP
|  58   | PHP, MySQL Bible
|  59   | The complete guide to SQL
|  62   | learn MySQL in 24 hours
|  64   | How to build websites
|  69   | SQL stored procedures guide
++++++++++++++++++++++++++++++++++++++
现在我要运行此查询:

SELECT book_id 
from books 
where book_title ilike '%sql%' 
    OR book_title ilike '%guide%' 
    OR book_title ilike '%complete%'
我希望得到以下结果:

++++++++++++++++++++++++++++++++++++++
book_id | met_conditions
++++++++++++++++++++++++++++++++++++++
|  59   | 3
|  69   | 2
|  62   | 1
|  58   | 1
|  54   | 1
其中,满足条件是指每个记录中满足的适用条件总数


我可以用SQL实现吗?如果是,如何进行

您可以在MySQL中同时添加这些条件:

select book_id,
       ((book_title ilike '%sql%') +
        (book_title ilike '%guide%') +
        (book_title ilike '%complete%')
       ) as metConditions
from books
where book_title ilike '%sql%' OR book_title ilike '%guide%' OR book_title ilike '%complete%';
这是因为MySQL在数字上下文中将布尔表达式视为整数,0表示false,1表示true。另一种方法是使用
case
表达式,这是在任何(合理的)数据库中都可以使用的


这种类型的查询最好使用全文索引。那么相关性就是你想要的指标。(注意:默认情况下,全文索引将忽略SQL,因为它有三个字母;设置“最小字长”参数可解决此问题。)

完全按照需要工作,但性能非常缓慢。搜索100万条记录将在11秒内返回50条记录。你有什么建议可以提高这种查询的速度吗?非常感谢@gordon linoff!我接受你的回答。@RaedN。因此,您需要一个全文索引,正如答案中所建议的那样。不幸的是,我们在MySQL 5.4上使用InnoDB表,因此我们无法使用全文索引,并且由于环境限制,我们无法升级服务器,因此我们正试图使用我们手中最好的方法来实现这一点。