如果我们要执行多个查询条件,比如检索price不高于5或者供应商是1001,1002的商品。我们可以使用where...or...语句:
select products.vend_id,prod_id,prod_price
from products
where prod_price<=5
or products.vend_id in (1001,1002);
但是我们还可以使用union将两个select语句合并起来:
mysql> select products.vend_id,prod_id,prod_price from products where prod_price<=5
-> union
-> select products.vend_id,prod_id,prod_price from products where products.vend_id in (1001,1002);
这两个检索语句结果一样。
注意:
如果我们不想取消这些行,将union改为union all.
若要排序,只能在最后一条select后面跟上order by.它作用于全部语句。
也可以稍后指定,不在创建的时候指定。
注意在导入数据的时候不要指定fulltext,因为更新索引需要花费时间。
使用例子:
select note_text from productnotes
where Match(note_text) Against(‘rabbit‘);
就可以匹配出出现‘rabbit‘的文本行。使用LIKE照样可以:
select note_text from productnotes
where note_text like ‘%rabbit%‘;
我们使用全文本搜索的优点在于:like返回的记录顺序没有特别的用处(或者说是规律)。而使用全文本搜索,我们是按匹配词的等级返回的。
看下面一条检索语句,我们把等级用数值表示出来:
select note_text,match(note_text) against(‘rabbit‘) as rank from productnotes \G;
如图所示,rank值为0的就是不包含匹配词‘rabbit‘的记录。我们返回顺序是优先级从高到底的顺序。
等级值:
除了查找出现匹配词的行之外,我们可能还需要检索出与这个词有关的行,但匹配的词却没有出现在这行中。
如我们要检索与‘anvils‘匹配的行:
mysql> select note_text from productnotes
-> where match(note_text) against(‘anvils‘);
这样我们只返回一条数据,其中包含‘anvils‘.
使用扩展查询时候:
至于是如何选择有用的词,则之后学习。
语法:
mysql> select note_text from productnotes
-> where match(note_text) against(‘anvils‘ with query expansion);
这次我们返回了7条记录:
原因如上图。
布尔文本搜索即使没有fulltext索引也可以使用。
布尔方式可以提供以下细节:
表达式分组。
select note_text from productnotes
-> where match(note_text) against(‘heavy‘ in boolean mode);
此条布尔查询和全文本搜索一致。但我们要如果需要排斥一个词呢?
mysql> select note_text from productnotes
-> where match(note_text) against(‘heavy -rope*‘ in boolean mode);
此条布尔查询就可以返回不以‘rope‘开头的含有‘heavy‘的记录。
实例:
原文:https://www.cnblogs.com/love-jelly-pig/p/10360130.html